简体   繁体   English

MySQL 从同一个表中选择不同的类别,但具有相同的限制

[英]MySQL select from the same table but from different category with the same limit

I want to select from the same table我想从同一张表中选择

  • articles where cat='Histoire' limit 12 cat='Histoire' 限制为 12 的文章
  • articles where cat='Cultures' limit 12 cat='Cultures' 限制 12 的文章
  • articles where cat='Sujet Divers' limit 12 cat='Sujet Divers' 限制 12 的文章

for this after searching i try the code bellow :为此,在搜索之后,我尝试使用以下代码:

SELECT * FROM makale WHERE cat='Histoire' LIMIT 12
UNION ALL
SELECT * FROM makale WHERE cat='Cultures' LIMIT 12
UNION ALL
SELECT * FROM makale WHERE cat='Sujet Divers' LIMIT 12
ORDER BY id DESC

but the code dnt work i get this erro :但代码 dnt 工作我得到这个错误:

Error
Static analysis:

1 errors were found during analysis.

Unexpected ordering of clauses. (near "LIMIT" at position 172)
SQL query: Copy Documentation

SELECT * FROM makale WHERE cat='Histoire' LIMIT 12 UNION ALL SELECT * FROM makale WHERE cat='Cultures' LIMIT 12 UNION ALL SELECT * FROM makale WHERE cat='Sujet Divers' LIMIT 12 ORDER BY id DESC

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UNION ALL
SELECT * FROM makale WHERE cat='Cultures' LIMIT 12
UNION ALL
SELECT' at line 2

can sameone show me the best way to do this Thank you可以告诉我最好的方法吗谢谢

Limit cannot appear anywhere other than at the end unless in sub queries eg限制不能出现在末尾以外的任何地方,除非在子查询中,例如

DROP TABLE IF EXISTS T;
CREATE TABLE T(ID INT, CATEGORY VARCHAR(20));
INSERT INTO T VALUES (1,'HISTOIRE'),(2,'HISTOIRE'),(3,'CULTURES'),(4,'SUJET DIVERS'),(5,'SUJET DIVERS'),(6,'SUJET DIVERS');

SELECT * FROM 
(SELECT * FROM T WHERE category='Histoire' LIMIT 2) A
UNION ALL
(SELECT * FROM T WHERE category='Cultures' LIMIT 2) 
UNION ALL
(SELECT * FROM T WHERE category='Sujet Divers' LIMIT 2) 
ORDER BY id DESC

+------+--------------+
| ID   | CATEGORY     |
+------+--------------+
|    5 | SUJET DIVERS |
|    4 | SUJET DIVERS |
|    3 | CULTURES     |
|    2 | HISTOIRE     |
|    1 | HISTOIRE     |
+------+--------------+
5 rows in set (0.001 sec)

You need subqueries:您需要子查询:

(SELECT * FROM makale WHERE category = 'Histoire' LIMIT 12)
UNION ALL
(SELECT * FROM makale WHERE category = 'Cultures' LIMIT 12)
UNION ALL
(SELECT * FROM makale WHERE category = 'Sujet Divers' LIMIT 12)
ORDER BY id DESC;

You can also write this using window functions, but that is not your question.您也可以使用窗口函数来编写它,但这不是您的问题。

Note: This returns an arbitrary 12 rows for each category.注意:这会为每个类别返回任意12 行。 I'm leaving the code as is, because this answers the question you have asked.我将代码保留原样,因为这回答了您提出的问题。 But if you want a particular set of 12 rows, then you should use an ORDER BY in each subquery.但是如果您想要一组特定的 12 行,那么您应该在每个子查询中使用ORDER BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM