1

我有两张桌子:

tickets

ticket_id, int(11), NO, PRI, , auto_increment
order_num, varchar(45), NO, , , 
user_id, int(11), YES, , , 
event_id, int(11), YES, , , 
number_of_tickets, varchar(4), YES, , , 
order_placed, timestamp, NO, , CURRENT_TIMESTAMP, 
payment_recd, enum('Yes','No'), YES, , No, 
payment_time, timestamp, YES, , , 

events

event_id, int(11), NO, PRI, , auto_increment
venue_id, int(11), YES, , , 
event_date, date, YES, , , 
event_time, time, YES, , , 
event_price, decimal(4,2), YES, , , 
event_capacity, int(11), YES, , , 
dateadded, timestamp, NO, , CURRENT_TIMESTAMP, 

我需要列出用户购买的门票并按活动日期订购,但我正在尝试的以下操作没有正确排序

select tickets.order_num as ordnum, tickets.event_id as tickid, tickets.number_of_tickets as numtix 
   from tickets, events
where  ((tickets.user_id = '1') and (tickets.payment_recd = 'Yes'))
  group by tickets.order_num 
order by events.event_date asc

有任何想法吗?

4

5 回答 5

2

您没有加入表格,因此它将列出两个表格中的所有行,请尝试:

select tickets.order_num as ordnum, tickets.event_id as tickid, tickets.number_of_tickets as numtix 
from tickets
inner join events on tickets.event_id = events.event_id
where ((tickets.user_id = '1') && (tickets.payment_recd = 'Yes'))
group by tickets.order_num order by events.event_date asc
于 2012-07-02T08:17:56.640 回答
1

首先,我建议您使用JOIN,因为您的方法太慢且JOIN最快,更安全,实际上是您能够使用和数据库正确编写的最有效的解决方案。

SELECT t.order_num, t.event_id, t.number_of_tickets 
FROM tickets t
INNER JOIN events e ON (t.event_id = e.event_id)
WHERE ((t.user_id = '1') && (t.payment_recd = 'Yes'))
GROUP BY t.order_num
ORDER BY e.event_date ASC
于 2012-07-02T08:18:09.440 回答
0

尝试:

select tickets.order_num as ordnum, tickets.event_id as tickid, tickets.number_of_tickets as numtix 
   from events
  inner join tickets on events.id = ticket.event_id
where  ((tickets.user_id = '1') and (tickets.payment_recd = 'Yes'))
  group by tickets.order_num 
order by events.event_date asc

你没有显示eventstickets表之间的关系,得到一个笛卡尔积。

于 2012-07-02T08:18:09.007 回答
0

您需要在 where 子句中使用“AND Tickets.event_id = events.event_id”。

您尚未指定如何连接这两个表,因此目前您正在执行完全连接。

于 2012-07-02T08:18:32.720 回答
0

尝试使用它

 select tickets.order_num as ordnum, tickets.event_id as tickid,
 tickets.number_of_tickets as numtix from tickets inner join events on
    tickets.event_id=events.event_id where
 ((tickets.user_id = 1) && (tickets.payment_recd = 'Yes'))
 group by tickets.order_num order by events.event_date asc

请考虑tickets.user_id是一个整数,你不能把它当作一个带有''的字符串......它必须像尝试使用它tickets.user_id = 1

于 2012-07-02T08:20:01.240 回答