Combine MySQL Queries in PHP
I have the following MySQL queries开发者_StackOverflow社区:
Query #1:
SELECT imgURL, imgTitle, FROM images
Query #2:
SELECT DISTINCT imgFamily FROM images
Query #3:
SELECT DISTINCT imgClass FROM images
I'm wondering if it is possible to combine them into one query? In other words, SELECT imgURL, imgTitle, DISTINCT imgFamily, and DISTINCT imgClass
.
When I attempted to do it as above (without the and
), it failed. Any suggestions?
The result I get is the following: MySql ErrorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT imgFamily FROM images
The result I expect is to not have an error, and have rows returned.
The distinct
keyword in MySQL is a synonym for distinctrow
- eg. If you want a 'select distinct'. you're going to get only the rows where the combination of fields has not yet appeared in the results. By selecting non-distinct fields, you won't get ANY distinct results. This has to be done as separate queries.
You can combine them with the UNION
keyword:
SELECT imgURL, imgTitle, FROM images
UNION
SELECT DISTINCT imgFamily, NULL FROM images
UNION
SELECT DISTINCT imgClass, NULL FROM images
but it's a really bad idea. All columns in subsequent queries must have the same type as columns from all subsequent queries, or some data may get truncated.
Generally, you shouldn't combine unrelated queries.
SELECT distinct imgURL, imgTitle, imgFamily, imgClass
FROM images
The above will give you unique row.
SELECT imgURL, imgTitle, imgFamily, imgClass
FROM images
This one will give you all data.
it is hard to figure out what you are trying to do.
精彩评论