我想将2个查询合并为一个。我想从last_name中提取一封信,并寻找以该字母开头的计数器。我的查询给了我一封以上的信,我不知道为什么。
SELECT CONCAT(LOWER(SUBSTR(country, 1, LENGTH(country) - 1)),
UPPER(substr(country, -1))) AS Kraj,
COUNT(C.country_id) AS ilosc
FROM city AS C
JOIN country AS CO ON C.country_id = CO.country_id
WHERE country LIKE
(SELECT CONCAT(LEFT(last_name, 1), '%')
FROM actor
ORDER BY RAND()
LIMIT 1)
GROUP BY C.country_id
HAVING COUNT(C.country_id) > 1;
答案 0 :(得分:0)
首先将其更改为INNER_JOIN会对您来说很容易理解:JOIN country AS CO ON C.country_id = CO.country_id第二个:您正在从表中提取数据,但看不到数据。如果您只想为该示例检索一个结果,则可以考虑使用DISTINCT
SELECT DISTINCT CONCAT(LOWER(SUBSTR(country, 1, LENGTH(country) - 1)),
UPPER(substr(country, -1))) AS Kraj,
COUNT(C.country_id) AS ilosc
FROM city AS C
INNER JOIN country AS CO ON C.country_id = CO.country_id
WHERE country LIKE
(SELECT CONCAT(LEFT(last_name, 1), '%')
FROM actor
ORDER BY RAND()
LIMIT 1)
GROUP BY C.country_id
HAVING COUNT(C.country_id) > 1;
答案 1 :(得分:0)
对于每个国家,DBMS都会评估WHERE
子句中的条件,从而一次又一次地执行子查询,并产生各种字母,而不仅仅是一个字母。
使用CROSS JOIN
代替随机提供一个字母。
SELECT
CONCAT(LOWER(SUBSTR(country, 1, LENGTH(country) - 1)), UPPER(substr(country, -1))) AS Kraj,
COUNT(C.country_id) AS ilosc
FROM city AS C
JOIN country AS CO ON C.country_id = CO.country_id
CROSS JOIN
(
SELECT CONCAT(LEFT(last_name, 1), '%') AS letter
FROM actor
ORDER BY RAND()
LIMIT 1
) the_one
WHERE country LIKE the_one.letter
GROUP BY C.country_id
HAVING COUNT(C.country_id) > 1;