我有两张桌子:
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
有什么想法吗?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
您没有显示events
和tickets
表格之间的关系,获取笛卡尔积。
答案 3 :(得分:0)
你的where子句中需要一个'AND tickets.event_id = events.event_id'。
您尚未指定如何加入这两个表,因此目前您正在进行完全加入。
答案 4 :(得分: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
并且请考虑ticket.user_id是一个整数,你不能把它表现为带有''的字符串...... 它必须像尝试使用ticket.user_id = 1