我不知道如何解释这个,我不会用到SQL ..这是我的查询,它不工作
select * from ao_addrcodes
JOIN a1_addrs on a1_addrid = ao_addrid left Join a2_name on a2_addrid = ao_addrid
where ao_codeid = 'DJ' and 'E' and 'A'
尝试获取表ao_addrid中的人员列表,他们的ao_codeid是“DJ”,“E”和“A”
所以弗雷德会在桌子上3次。他的a2_addrid会是一样的但是他的 ao_codeid会有所不同
每个人都有多个记录,如果他们有多个ao_codeid的
帮助?
修改
ao_codeid,a2_addrid
'DJ', '525'
'E', '525'
'A', '525'
'DJ', '52'
'A', '25'
'E', '25'
因此,从上面的数据我只想看到用户525出现。不是52或25。
我正在使用MySQL
答案 0 :(得分:1)
如果您使用的是SQL Server,那么您的WHERE语句不正确:
SELECT *
FROM ao_addrcodes
JOIN a1_addrs ON a1_addrid = ao_addrid
LEFT JOIN a2_name ON a2_addrid = ao_addrid
WHERE ao_codeid IN('DJ', 'E', 'A')
或者你可以这样做
WHERE ao_codeid = 'DJ'
OR ao_codeid = 'E'
OR ao_codeid = 'A'
编辑1
我会做这样的事情:
--Create a CTE that counts eligible records
WITH CodeCount AS
(
SELECT ID, --this represents your 525 data
COUNT(*) AS CodeCount
FROM [your table]
WHERE code IN('DJ', 'E', 'A')
GROUP BY ID
)
SELECT *
FROM [your table]
INNER JOIN CodeCount ON [your table].ID = CodeCount.ID
WHERE CodeCount = 3
编辑2
由于您编辑了帖子以表示您正在使用MySQL,这将是我的解决方案:
SELECT *
FROM ao_addrcodes
JOIN a1_addrs ON a1_addrid = ao_addrid
LEFT JOIN a2_name ON a2_addrid = ao_addrid
INNER JOIN (
SELECT ID,
COUNT(*) AS EligibleCount
FROM ao_addrcodes
WHERE ao_codeid IN('DJ', 'E', 'A')
GROUP BY ID
) a ON a.ID = ao_addrcodes.ID
WHERE a.EligibleCount = 3
答案 1 :(得分:1)
在哪些表格中跟踪哪些字段有点困难,但我会试一试。问题是大多数人认为你想要寻找关于如何使用IN运算符的教科书答案,但是你需要更复杂的东西。
我认为做你想做的最简单的方法是:
SELECT *
FROM a2_name
WHERE EXISTS (
SELECT COUNT(DISTINCT ao_codeid) FROM ao_addrcodes
JOIN a1_addrs on a1_addrid = ao_addrid
LEFT JOIN a2_name on a2_addrid = ao_addrid
WHERE ao_codeid IN ('DJ', 'E', 'A') AND a2_addrid = ao_addrid
HAVING COUNT(DISTINCT ao_codeid) = 3
)
或者不那么复杂并仍然按照您的意愿行事(但我不确定您想要返回的字段,只需将a2_name.name替换为您想要返回的所有字段的列表,因为未提供架构:
SELECT a2_name.name
FROM ao_addrcodes
JOIN a1_addrs on a1_addrid = ao_addrid
LEFT JOIN a2_name on a2_addrid = ao_addrid
WHERE ao_codeid IN ('DJ', 'E', 'A')
GROUP BY a2_name.name
HAVING COUNT(DISTINCT ao_codeid) = 3
答案 2 :(得分:0)
where ao_codeid = 'DJ' OR ao_codeid = 'E' OR ao_codeid = 'A'
答案 3 :(得分:0)
或者找到DJ记录然后检查另外2个存在吗?
SELECT * FROM ao_addrcodes a
JOIN a1_addrs ON a1_addrid = a.ao_addrid
LEFT JOIN a2_name ON a2_addrid = a.ao_addrid
WHERE ao_codeid = 'DJ'
AND EXISTS (SELECT * FROM ao_addrcodes x WHERE ao_codeid = 'E' and x.ao_addrid= a.ao_addrid) AND
AND EXISTS (SELECT * FROM ao_addrcodes x WHERE ao_codeid = 'A' and x.ao_addrid= a.ao_addrid)
注意:其他基于计数的解决方案仅在ao_addrid&上有唯一约束时才有效。 ao_codeid。
答案 4 :(得分:-2)
尝试获取表ao_addrid中的人员列表 他们的ao_codeid是'DJ','E'和'A'
如果我已经理解了你的问题,你的where子句使用AND应该在哪里使用OR,如果我已经理解你的问题,那么措辞不是很明确。
where ao_codeid in ('DJ','E','A')
使用SQL时,在将其翻译成查询之前,当您尝试用日常英语(或您说的任何自然语言)定义问题时,必须非常密切关注您的AND和OR。