English 中文(简体)
Mysql加入问题
原标题:Mysql joins problem

我利用这一询问选择所有条款:

SELECT articles.*,categories.category_name,users.username,tags.tag 
FROM articles 
LEFT JOIN `categories` ON articles.category_id = categories.category_id 
LEFT JOIN `users` ON articles.author_id = users.user_id 
LEFT JOIN `tags` ON articles.article_id = tags.article_id 
ORDER BY articles.date_added DESC

我有另一个表格<代码>comments,我想计算一下有多少评论,在该表中该文章的背面=文章的背面。 我与坦桑尼亚联合国合作组织一道进行了尝试,但结果只有一次。 我怎么能用一个问题来做到这一点?

问题回答

You can use a subquery in the SELECT clause:

SELECT articles.*,categories.category_name,users.username,tags.tag, (SELECT count(*) FROM comments c WHERE c.article_id = articles.article_id) as comments_count

如Arnaud576875所述,你可以使用一个子序列提取摘要数据。

我从阁下那里听到的两件事情实际上不是问题的一部分,但仍然值得指出。

  • you can use a table alias to shorten your SQL and make it more readable.

因此,

SELECT articles.*,categories.category_name,users.username,tags.tag 
FROM articles 
LEFT JOIN `categories` ON articles.category_id = categories.category_id 
LEFT JOIN `users` ON articles.author_id = users.user_id 
LEFT JOIN `tags` ON articles.article_id = tags.article_id 
ORDER BY articles.date_added DESC

页: 1

SELECT a.*, c.category_name, u.username, t.tag 
FROM articles a
LEFT JOIN `categories` c ON a.category_id = c.category_id 
LEFT JOIN `users` u ON a.author_id = u.user_id 
LEFT JOIN `tags` t ON a.article_id = t.article_id 
ORDER BY a.date_added DESC
  • I would drop SELECT * and select only the fields that you actually are going to use. This also helps with readability of your code.




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签