我有以下sql语句:
SELECT
COUNT(table2.programName),
table2.programName
FROM
table1
LEFT JOIN
table2
ON
table1.programID = table2.programID
WHERE
table1.MemberID = 12345
AND
table2.programName = (table2.programName associated with dynamic table2.programID)
我确实意识到最后一个AND语句目前无效,但这是我似乎无法理解的。虽然我可以通过插入已知值来成功执行查询,但是需要动态生成查询(使用php完成),并且值将显示为变量。我只在括号中显示我想要完成的事情。
任何想法如何在单个sql语句中找到与括号中的programID相关联的programName?
因此,在进行更多测试时,我想我可能已找到答案但不确定这是否是“好”的做法。这是我的代码:
SELECT
COUNT(table2.programName),
table2.programName
FROM
table1
LEFT JOIN
table2
ON
table1.programID = table2.programID
WHERE
table1.MemberID = 12345
AND
table2.programName = (SELECT table2.programName FROM table2 WHERE table2.programID = $id);
答案 0 :(得分:2)
使用:
SELECT t2.programname,
COUNT(t2.programname)
FROM TABLE2 t2
LEFT JOIN TABLE1 t1 ON t1.programid = t2.programid
AND t1.memberid = 12345
WHERE t2.programid = $id
GROUP BY t2.programname
答案 1 :(得分:0)
假设table2具有自我关系,这是一个可能的解决方案:
SELECT
COUNT(table2.programName),
table2.programName
FROM
table1
LEFT JOIN
table2
ON
table1.programID = table2.programID
LEFT JOIN
table2 as t2again
ON
t2again.mysteriousAssociationChild = table2.mysteriousAssociationFather
WHERE
table1.MemberID = 12345
AND
table2.programName = t2again.programName
诀窍是SQL允许根据需要多次使用相同的表。在这个说明性的案例中,自我关系由mysteriousAssociationChild和mysteriousAssociationFather表示,其中一个也可能是programID(但这会破坏一些神秘感:)。
如果有些事情不清楚,请告诉我。
答案 2 :(得分:0)
如何直接查看?
SELECT
COUNT(table2.programName),
table2.programName
FROM
table1
LEFT JOIN
table2
ON
table1.programID = table2.programID
WHERE
table1.MemberID = 12345
AND
table2.programID = $id;
答案 3 :(得分:0)
这显示表1中所有行的计数,其中MemberID = 12345,引用具有ProgramID = $id
的程序。
SELECT
COUNT(table2.programName),
table2.programName
FROM table1
LEFT JOIN table2
ON table1.programID = table2.programID
WHERE table1.MemberID = 12345 AND table2.ProgramID = $id
GROUP BY table2.programName