Mysql relationship one-many get data with more where clause - php

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;

Related

using union on two tables but renaming the field

I have two tables that have an id field with the same name. I didn't think I'd ever need to mix the two but there's one page where I need to. I can't join the tables because they both have completely separate data and no fields in common.
I can union them but the ID field is the same name and many identical numbers (which do not relate). I can't change the name in the tables but I need the field names to be different when put into a variable (using PHP).
I tried something like this:
SELECT date, id as id1
FROM football
UNION
SELECT date, id as id2
FROM basketball
ORDER BY date
But that just gives me one field (id1). I need the result to be in such a way that I can do this:
foreach ($rows as $row) {
if (!empty($row['id1'])) {
$id = $row['id1'];
$sport = "football";
} else {
$id = $row['id2'];
$sport = "basketball";
}
echo "my number is $id and I play $sport";
}
From MySQL Union Syntax
The column names from the first SELECT statement are used as the
column names for the results returned.
You could assign sport in your query:
SELECT date, id, 'football' as sport
FROM football
UNION
SELECT date, id, 'basketball' as sport
FROM basketball
ORDER BY date

Mysql select from table by comparing value in another table

I have two tables first and second.
first Table:
ID NAME ADDRESS
1 test testing address
2 test1 testing address
3 test2 testing address
4 test3 testing address
second Table:
T_ID Partner_id date
1 2 12345678
3 4 32164584
If input T_id is given. Then corresponding Partner_id is taken and it is compared with the ID from first table and corresponding row should be selected.
Can you please tell me.
In php I can write this with two queries but I want it to be in a single query.
Queries in php:
$q=mysqli_query($conn, "SELECT Partner_id from second where T_ID=1");
$qa=mysqli_fetch_array($q);
$w=mysqli_query($conn, "SELECT * from first where ID=$qa[0]");
But, how to combine this two statements?
The specified result can be returned using a query with a join operation.
SELECT f.*
FROM first f
JOIN second s
ON s.Partner_id = f.ID
WHERE s.T_ID=1
Note that there is a potential for this to return more rows that the original, if the first query returns more than one row. (That is, we don't assume that T_ID is unique in second, or that every row with a given T_ID value will have identical values for Partner_id.)
There are other query patterns that will return an equivalent result, but the join operation is the normative pattern.
try to use union ,see this this link
where The SQL UNION operator combines the result of two or more SELECT statements.
SELECT * FROM first WHERE ID IN( SELECT Parent_id FROM second WHERE T_ID = 1 )
or
SELECT * FROM first WHERE ID = ( SELECT Parent_id FROM second WHERE T_ID = 1 )
SELECT * FORM first_table AS f
JOIN second_table AS s
ON s.parent_id =f.id
WHERE s.T_ID = $id

PHP - Combining 2 Queries to 1 Result Output

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`

SQL Query: do I need two queries or can I use a nested subquery

This question may have been asked before but I don't really know what verbiage to search with.
I have a mysql DB that has a table with 3 columns [ID, fieldName and fieldValue] that is used to describe attributes of objects in another table. The ID field stores the foreign key of object in the other table and the fieldName and fieldValue store things like title, description, file size and summary.
I am trying to write a query that returns rows where a fieldName and fieldValue pair match known values and the returned row ID has a another distinct fieldValue in another row. Right now I am accomplishing it with two queries and an if statement. Here is the sudo code:
$result = SELECT * FROM table_a WHERE fieldName = 'title' and fieldValue = 'someTitle'
$test = SELECT * FROM table_a WHERE fieldValue = 'someValue' and id = '{$result['id']}'
if ($test) {
/* Result Found */
}
You can self-join the table:
SELECT * FROM table_a AS s1
JOIN table_a AS s2 USING (id)
WHERE
s1.fieldName = 'Title' AND s1.fieldValue = 'someTitle'
AND s2.fieldValue = 'someValue'
What you said translated in sql would be:
SELECT b.*
FROM table_a a
INNER JOIN table_a b ON a.id = b.id
WHERE a.fieldName = 'title'
AND a.fieldValue = 'someTitle'
AND a.fieldValue <> b.fieldValue
This gets you the rows in table_a that have the same id as the row with you predefined values, but with a different fieldValue. This assumes that id is not the primary key, otherwise there will not be another row with the same id, but it looks in your question that this isn't the case. (If you want to check for a specific value you can do: AND b.fieldValue = 'someValue' in the last line)

How could I compare these database values in PHP?

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.)

Categories