+-------------+--------------+----------+-------+
| ticketRefNo | nameOnTicket | boughtBy | event |
+-------------+--------------+----------+-------+
| 38 | J XXXXXXXXX | 2 | 13 |
| 39 | C YYYYYYY | 1 | 13 |
| 40 | M ZZZZZZZZZZ | 3 | 14 |
| 41 | C AAAAAAA | 3 | 15 |
| 42 | D BBBBBB | 3 | 16 |
| 43 | A CCCCC | 3 | 17 |
+-------------+--------------+----------+-------+
+-------------+------------------+--------------+---------------------+--------+
| ticketRefNo | cardNo | cardHolder | exp | issuer |
+-------------+------------------+--------------+---------------------+--------+
| 38 | 4444111133332222 | J McKenny | 2016-01-01 00:00:00 | BOS |
| 39 | 4434111133332222 | C Dempsey | 2016-04-01 00:00:00 | BOS |
| 40 | 4244111133332222 | M Gunn-Davis | 2018-02-01 00:00:00 | RBS |
+-------------+------------------+--------------+---------------------+--------+
+-------------+-------------+----------+
| ticketRefNo | boxOfficeID | paidWith |
+-------------+-------------+----------+
| 41 | 1 | card |
| 42 | 2 | cash |
| 43 | 3 | chequ |
+-------------+-------------+----------+
我有一个包含上述数据的数据库。它代表了购票系统。我希望能够看到以活动名称和boxOfficeID或借记卡发行者购买的门票列表。
我试过运行以下代码,但无济于事。
SELECT t.ticketRefNo AS 'Reference', t.event AS 'Event',
IF(COUNT(SELECT * FROM Online WHERE t.ticketRefNo=o.ticketRefNo;) >= 1,
o.issuer, InPerson.boxOfficeID) AS 'Card Issuer or Box Office'
FROM Ticket AS t, InPerson, Online AS o
WHERE t.ticketRefNo=o.ticketRefNo;
提前干杯!
答案 0 :(得分:2)
一些注意事项:分号字符的语法无效;如果您需要分隔子查询,请将其包装在parens中。转义列别名就像你要转义任何其他标识符:使用反引号,而不是单引号。单引号用于字符串文字。
假设issuer
表中的Online
为非空,并且假设ticketRefNo
和Online
表中的InPerson
都是唯一的,则可以做这样的事情:
SELECT t.ticketRefNo AS `Reference`
, t.event AS `Event`
, IF(o.ticketRefNo IS NOT NULL,o.issuer,i.boxOfficeId)
AS `Card Issuer or Box Office`
FROM Ticket t
LEFT
JOIN InPerson i
ON i.ticketRefNo = t.ticketRefNo
LEFT
JOIN Online o
ON o.ticketRefNo = t.ticketRefNo
使用外部联接操作查找InPerson
和Online
表中的匹配行,并使用条件测试查看是否从Online
表中获得了匹配的行。如果找不到匹配的行,将返回NULL。
答案 1 :(得分:1)
将一列连接到两个不同的表并且两个表中的每一个都有一些值,这不是一个好主意。
但无论如何这里仍然存在:
( SELECT ... FROM Ticket t JOIN InPerson x USING(ticketRefNo) ... )
UNION ALL
( SELECT ... FROM Ticket t JOIN Online x USING(ticketRefNo) ... )
ORDER BY ...
ALL
假设InPerson和Online永远不会有任何重叠的ticketRefNos。
最后的ORDER BY是为了你想要排序的东西,虽然我在你尝试的SELECT中看不到它。
两个SELECT必须具有相同的列数。