I have a database with 2 tables. one called "object" and the other called "object_meta".
now i want to save additional fields depending to an entry in the "object" table inside the "object_meta" table. until now i do so with 2 queries.
1st query:
SELECT * FROM object WHERE id=$id
and the 2nd query:
SELECT * FROM object_meta WHERE object_id=$id
and then i put this 2nd query inside a new field of the 1st array called ex: meta_fields
including the array of the query to "object_meta"
$array[$id]['additional_fields'][$add_field[key]] = $add_field[value];
please can someone show me how to do this with a join?
thx a lot :D
SELECT object.*, object_meta.*
FROM object
INNER JOIN object_meta
ON object.id = object_meta.object_id
WHERE object.id = ?
Adjust the INNER JOIN to a LEFT JOIN if object_meta does not carry information for every object. The fields of object_meta will then be NULL if there is no matching row.
Note that this will not put the values into addtional_fields, but on the same level as all the other values.
This is how you can do it, however I would suggest to select only the required fields from both tables which you want to display and you can do as table_name.col_name1,table_name.col_name2 etc and can use where condition on first table col name with the input value.
select * from `object`
inner join `object_meta` on `object_meta`.`object_id` = `object`.`id`
Related
I have 2 table in my mysql database
1 is for registry all personal information with ID autoincrement
2 is for some attribute with value and have ID_Anagrafica = ID
My question is: If i want to search in first table only the registry with some attribute value on the second table, how can i do this?
example:
First registry table:
Second table for attribute with value:
ID_Anagrafica matches with ID in registry
There is a query that return ID with where clause on second table:
SELECT *
FROM "first table"
WHERE "secondTable".valore = "value"
AND "secondTable".valore = "value";
This would be one way... The values for the in and the value for the count could be variables passed in however, as you will always know what values you're passing in and how many there are...
SELECT *
FROM First A
INNER JOIN (SELECT ID_anafrafica
FROM Second
WHERE Valore in ('value1','Value2')
Group by ID_anafrafica
having count(ID_Anafrafica) = 2) B
on A.ID = B.ID_anafrafica
What I don't like about this is you're not keying off of ID_Attributo and I think you should be if you're looking for the Valore of the attribute
This should scales better in performance and maintainability than adding additional joins for each element.
You should use JOIN for that.
SELECT a.* FROM "first table" AS a <br>
JOIN "second table" AS b ON a.ID = b.ID_Anagrafica <br>
WHERE b.valore = "value" <br>
GROUP BY a.ID;
I would like to get one value instead of all values when they have the same name.
within an sql query. Im using fullcalendar. and have two tables one for the events(evenement) and one for the receiver(evenementontvanger).
evenementontvanger:
id idEvent
1 231
2 231
3 231
evenement:
id title
231 hello
I would like to show only one title not 3
my sql query:
"SELECT
*
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`"
You can use distinct to do so as
SELECT distinct `evenementontvanger`.`idEvent`,`evenement`.`title`
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`;
How ever the above will not bother about idWerknemer and if you want to display them as group use Group_concat as
SELECT `evenementontvanger`.`idEvent`,
`evenement`.`title`,
group_concat(`evenementontvanger`.`idWerknemer`) as `idWerknemer`
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`
Group By `evenementontvanger`.`idEvent`
Check the demo here http://sqlfiddle.com/#!2/290b4/13
Use SELECT DISTINCT on your query to eliminate duplicates :
The ALL and DISTINCT options specify whether duplicate rows should be
returned. ALL (the default) specifies that all matching rows should be
returned, including duplicates. DISTINCT specifies removal of
duplicate rows from the result set. It is an error to specify both
options. DISTINCTROW is a synonym for DISTINCT.
From MySQL docs
use either top 1
OR
select distinct
I have a reviews table that contains three ways to rate an item. The items themselves then have three columns to hold the average for each value respectively.
I could do this using three nested queries in an update query, but I feel like this is inefficient... Is there a way to update them all at once?
So far I've used this as my select query:
SELECT AVG(rating_1),AVG(rating_2),AVG(rating_3) FROM items_reviews WHERE item_id = 1
I just don't know how to use the result of that query to update an item row.
You could use an join in the UPDATE:
UPDATE items a
INNER JOIN
(
SELECT
item_id,
AVG(rating_1) AS avg1,
AVG(rating_2) AS avg2,
AVG(rating_3) AS avg3
FROM items_reviews
WHERE item_id = 1
GROUP BY item_id
) b ON a.item_id = b.item_id
SET
a.avgrating1 = b.avg1,
a.avgrating2 = b.avg2,
a.avgrating3 = b.avg3
What i want, to display rows from a table which is selected by a field from other table single value, lets say to display images from a table by last category id.
I have this type of query, but this return me all matching keys rows, if i inset LIMIT 1 then it return one row...
SELECT i.prof_image FROM profile_images i
JOIN images_cat cat ON (cat.cat_id = i.cat_id)
GROUP BY i.prof_image;
//OR LIMIT 1;
Any idea to fix this problem. (i.e. displaying the latest category images)?
This will work for your specific example.. If you need to be more selective, then please post some more details..
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
SELECT * FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.id
This query will grab all things in table_2 that have the same id value.
Note that it is a LEFT JOIN - which means that if there are no matching values in table_2, it will still return the values from table_1.
What is your intent with using last()?
Hope this helps.
So a user selects from a drop down list a value. I take this value, put it into a variable, then select from the database the ID value of that table A holding the selected value also.
So now I'm trying to use that ID value to get to a many-to-many relationship table that has the selected value from table A to a different table B. The many-to-many relationship table has both IDs. How can I compare this using PHP?
So it would be like:
$A = $_POST['a'];
$sql = "SELECT a, aID from TABLEA WHERE a = $A";
What do I do then to compare the aID with the many-to-many relationships table, then get the other ID in that table and then take that ID to get values from table B?
You can do this with a join in your SQL:
SELECT table_b.* FROM ab_association
LEFT JOIN table_b ON table_b.id = ab_association.b_id
WHERE ab_association.a_id = $specified_id;
That assumes that your many-to-many join table is called ab_association and has two columns, one called a_id that corresponds to table_a.id, and b_id that corresponds to table_b.id.
Update: I removed the table name aliases since they seem to be confusing you.
Another Update: In PHP, here's how you would do that (sans business logic):
<?
// connect to db here
$a_id = mysql_real_escape_string($_POST['a_id']);
$result = mysql_query("SELECT table_b.* FROM ab_association LEFT JOIN table_b ON table_b.id = ab_association.b_id WHERE ab_association.a_id = $a_id;");
// in your view/template
while(false !== (mysql_fetch_object($result))) {
// build your output for each row
}
?>
SELECT *
FROM table_a
LEFT JOIN ab_association ON table_a.aID = ab_association.aID
LEFT JOIN table_b ON table_b.bID = ab_association.bID
WHERE table_a.a = $A
Notes:
I used some underscores in tablenames, so table_a instead of TABLEA (just like Coreyward did) to distinguish between sql and names
You should specify the columns you need instead of 'SELECT *' if many columns aren't needed
You can use JOIN instead of LEFT JOIN if you want get an empty recordset when no match in the many-to-many is found. (Using a LEFT JOIN has the advantage you still have access to the columns in table_A)
it is never wise to use $_POST-vars directly in your queries, this is a serious security risk (SQL injection.)