I have one query that INNER JOINs Table A with Table B and Table C, and I have another query that INNER JOINs Table A with Table D. I could achieve what I want to do by merging the 2 results, removing duplicates and ordering them in PHP code, but I want to know if MySQL has this functionality, I also think it'd be faster and easier to code once I understand it. Essentially, I want to have the results from Query 1 OR from Query 2. Perhaps the following will help:
Query 1:
SELECT pkAssociation, associations.strNameEn, associations.strNameFr
FROM associations
INNER JOIN eventassociations ON fkAssociation = pkAssociation
INNER JOIN events on fkEvent = pkEvent
WHERE events.enumDeleted = 'no'
GROUP BY pkAssociation
Query 2:
SELECT pkAssociation, associations.strNameEn, associations.strNameFr
FROM associations
INNER JOIN associationprograms AS aprogs ON aprogs.fkAssociation = associations.pkAssociation
GROUP by pkAssociation
The tables don't have anything else of relevance that don't show up in the query. I'm sorry if I'm not asking this correctly, I don't even know how to ask a question about this properly. If the column names or sample data is needed, then I can provide some. Sorry for the inconvenience and long post.
You want the UNION DISTINCT statement, placed between the two queries. This will combine the result sets from both and remove duplicates. You can then place your ORDER BY clause after all UNIONS (if you have one).
For example:
SELECT col1, col2 FROM tableA
UNION DISTINCT
SELECT col1, col2 FROM tableB
ORDER BY col2 DESC
Related
I have two tables : items and comments.
I want to select all items which a user commented on.
For simplicity, lets assume the items table has two columns : item_id and item_content. Let the comments table have 3 columns user_id, item_id and comment_content.
I am given the user_id of the commenting user, I need to first select all the item_id from the comments table, where user_id = myUserId.
This is a basic query SELECT item_id FROM comments WHERE user_id = '$myUserId'.
Then I need to select the item_content for each item_id returned by the previous query.
I was thinking of doing a while($row = $my_first_query->fetch_array()) loop, and inside of it doing something like SELECT item_content FROM item WHERE item_id = $row["item_id"]
however this is a bit messy and I was wondering if there was a simpler way of doing this, by combining the two queries into one.
Use an INNER JOIN:
SELECT t1.*
FROM items t1
INNER JOIN comments t2
ON t1.item_id = t2.item_id
WHERE t2.user_id = myUserId
The approach you suggested of first querying the comments table and then looping over the result set is inefficient. In a join, MySQL can handle this algebra much faster than your PHP code.
Depending of what you want to do exactly, you can just use a JOIN clause. The "header" table info will be found within all rows, so it might not be what you want to do.
Another way would be to run two distinct queries, the first one unchanged and the second one with a join. You would then have one result with the header, and the other with all the details that you could go through. It's more performant than run the same query over and over network wise.
Current query:
select * from `table1` where MATCH (`product_name`) AGAINST ('test' IN BOOLEAN MODE) AND `price` BETWEEN 0 AND 1000 order by MATCH (`product_name`) AGAINST ('test' IN BOOLEAN MODE) desc, `price` DESC LIMIT 0, 30
How can I run the above query on multiple tables with the same fields? eg table2, table3, table4
Would the query be faster if I were to combine all the data from all tables into 1 single table instead of multiple tables? Or would it make no difference at all?
Answer to 1st question : You can use JOINS in MySQL,that combines table as you say.
Answer to 2nd question :
One way :
SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1, table2
WHERE
table1.foreignkey = table2.primarykey
AND (some other conditions)
Second way :
SELECT
table1.this, table2.that, table2.somethingelse
FROM
table1 INNER JOIN table2
ON table1.foreignkey = table2.primarykey
WHERE
(some other conditions)
The WHERE syntax is more relational model oriented where INNER JOIN is ANSI syntax which you should use.
The first query using WHERE become much much more confusing, hard to read, and hard to maintain once you need to start adding more tables to your query. Imagine doing that same query and type of join on four or five different tables ... it's a nightmare.
However, depending on the query optimizer, they may have the same meaning to the machine.
You should always code to be readable.
That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause on the result set obtained from JOINS.
Hope this helps
What I want to do is to query three separate tables into one row which is identified by a unique reference. I don't really have full understanding of the Join clause as it seems to require some sort of related data from each table.
I know I can go about this the long way round, but can not afford to lose even a little efficiency. Any help would be greatly appreciated.
Table Structure
package_id int(8),
client_id int(8),
unique reference varchar (40)
Each of the tables have essentially the same structure. I just need to know how to query all three, for 1 row.
If you have few tables that are sharing the same or similar definition, you can use union or union all to treat them as one. This query will return rows from each table having requested reference. I've included OriginTable info in case your code will need to refer to original table for update or something else.
select 'TableA' OriginTable,
package_id,
client_id
from TableA
where reference = ?
union all
select 'TableB' OriginTable,
package_id,
client_id
from TableB
where reference = ?
union all
select 'TableC' OriginTable,
package_id,
client_id
from TableC
where reference = ?
You might extend select list with other columns, provided that they have the same data type, or are implicitly convertible to data type from first select.
Let's say you have 3 tables :
table1, table2 and table3 with structure
package_id int(8),
client_id int(8),
unique reference varchar (40)
Let's assume that column reference is unique key.
Then you can use this:
SELECT t1.exists_row ,t2.exists_row ,t3.exists_row FROM
(
(SELECT COUNT(1) as exists_row FROM table1 t1 WHERE
t1.reference = #reference ) t1,
(SELECT COUNT(1) as exists_row FROM table1 t2 WHERE
t2.reference = #reference ) t2,
(SELECT COUNT(1) as exists_row FROM table1 t3 WHERE
t3.reference = #reference ) t3
) a
;
Replace #reference with actual value of unique key
or when you provide output of
SHOW CREATE TABLE
I can rewrite SQL with actual query
It is entirely possible to create a join between tables using a where clause. In fact this is often what I do as I find it leads to clearer information of what you are actually doing, and if you don't get the results you expect you can debug it bit by bit.
That said however a join is certainly a lot quicker to write!
Please bear in mind I'm a bi rusty on SQL so I may have missed remembered, and I'm not going to include any code as you haven't said what DBMS you are using as they all have slightly different code.
The thing to remember is that the join functions on a column with the same data (and type) within it.
It is much easier if each table has the 'joining' field named the same, then it should be a matter of
join on <nameOfField>
However if you wish to use field that have different names in the different tables you will need to list the fully qualified names. ie tableName.FieldName
If you are having trouble with natural, inner and outer, left and right, you need to think of a venn diagram with the natural being the point of commonality between the tables. If you are using only 2 tables inner and outer are equivalent to left and right (with each table being a single circle in the venn diagram) and left and right being the order of the tables in your list in the main part of your select (the first being the left and the second being the right).
When you add a third table this is where you can select any of the cross over section using these keywords.
Again however I have always found it easier to do a primary select and create a temp table, then perform my next join using this temp table (so effectively only need to use natural or left and right again). Again I find this easier to debug.
The best thing is to experiment and see what you get in return. Without a diagram of your tables this is the best I can offer.
in brief...
nested selects where field = (select from table where field = )
and temp tables
are (I think) easier to debug... but do take more writting !
David.
array_of_tables[]; // contain name of each table
foreach(array_of_tables as $val)
{
$query="select * from `$val` where $condition "; // $conditon
$result=mysqli_query($connection,$query);
$result_row[]=mysqli_fetch_assoc($result); // if only one row going to return form each table
//check resulting array ,for your row
}
SELECT * FROM table1 t1 JOIN table2 t2 ON (t2.unique = t1.unique) JOIN table3 t3 ON (t3.unique = t1.unique) WHERE t1.unique = '?';
You could use a JOIN like this, assuming all three tables have the same unique column.
I have a table with around 15 columns. What I would like to be able to do, is select a range of IDs and have all column data that is the same, presented to me.
At the minute, I have it structured as the following:
SELECT id, col_a, col_b ... count(id)
FROM table
GROUP BY col_a, col_b ...
Which returns rows grouped together that have identical data within all the rows - which is half what I want, but ideally I would like to be able to get a single row with either the value (if it's the same for every row id) or NULL if there is a single difference.
I'm not sure that it is possible, but I would rather see if it's doable in an SQL query than write some looping logic for PHP to go through and check each row's similarity.
Thanks,
Dan
UPDATE:
Just to keep this up-to-date, I worked through the problem by writing a PHP function that would find which were duplicates and then display the differences. However I have now since made a table for each column, and made the columns as references to the other tables.
E.G. In MainTable, ColA now refers to the table ColA
I'm still solving the problem with the PHP for the time being, mainly as I think it still leaves the problem mentioned above, but at least now Im not storing duplicate information.
Its a hairy thing to do, but you could do it similarly to how David Martensson suggested, I would write it like this, however:
Select a.id, a.col1, a.col2, a.col3
FROM myTable a, myTable b
WHERE a.id != b.id
and a.col1 = b.col1
and a.col2 = b.col2
and a.col3 = b.col3
That would give you the ids that are unique, but each result would have the same values for columns 1, 2, and 3. However, I agree with some of the commenters to your question that you should consider an alternative data structure, as this could better take advantage of an RDBMS model. In that case you would want to have 2 tables:
Table name: MyTableIds
Fields: id, attrId
Table name: MyTableAttrs
Fields: attrId, attr1, attr2, attr3, ect
In general, if you have data that is going to be duplicated for multiple records, you should pull it into a second table and create a relationship so that you only have to store the duplicated data 1 time and then reference it multiple times.
Make a join to a subquery with the group by:
SELECT a.id, b.col_a, b.col_b ... b.count)
FROM table a
LEFT JOIN (
SELECT id, col_a, col_b ... count(id) "count"
FROM table GROUP BY col_a, col_b ...
)b on a.id = b.id
That way the outer will select all rows.
If you still want to group answers you could use a UNION instead
SELECT id, col_a ...
WHERE id NOT IN ("SUBQUERY WITH GROUP BY")
UNION
"SUBQUERY WITH GROUP BY"
Not the nicest solution but it should work
It seems doable from how I have understood your question.
And here's a possible pattern:
SELECT
/* GROUP BY columns */
col_A,
col_B,
...
/* aggregated columns */
CASE MIN(col_M) WHEN MAX(col_M) THEN MIN(col_M) ELSE NULL END,
CASE MIN(col_N) WHEN MAX(col_N) THEN MIN(col_N) ELSE NULL END,
...
COUNT(...),
SUM(...),
WHATEVER(...),
...
FROM ...
GROUP BY col_A, col_B, ...
What I want to do is get the data from two different tables (table1 and table2) where row1 = 'test' in both of the tables
You'll want to use an INNER JOIN here - something along these lines (can't tell you for sure since you didn't give the structure of your tables)...
SELECT * FROM thread t
INNER JOIN post_display pd ON pd.threadid = t.threadid
WHERE t.threadid = 2
ORDER BY t.threadid DESC
Note: SELECT * can be very bad if you're selecting a bunch of fields you're never going to need. Once you have the query working, narrow down your select to the specific fields you're looking to work with.
More info on JOIN syntax for MySQL is available here: http://dev.mysql.com/doc/refman/5.1/en/join.html
I'm not quite sure what you're asking, but if you want to fetch columns from multiple tables at once (and it sounds like you're saying rows when you mean columns) you probably want a JOIN, which is an SQL feature
I am not getting what you are asking about.. but.. i can give u suggestion on you asked question.. u can try this.. have a look
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.t1id
WHERE t1.row1 like 'test' AND t2.row like 'row';