Combining results on a MySQL INNER JOIN into one PHP array - php

I have two tables that I would like to join into one, but not all the fields. I've used INNER JOIN with some success, but can't get the exact results I need. Essentially, when using PHP to return results, I would like the key to be the 'meta_key' value.
Below are the two tables I want to combine:
USERS
+--------+-----------------+------------------+----------------+
| ID | username | first_name | last_name |
+--------+-----------------+------------------+----------------+
| 2 | hthompson | Hunter | Thompson |
| 7 | coak | Carol | Oak |
| 8 | delk | Dannie | Elk |
| 9 | mride | Mark | Ride |
| 10 | kken | Kyle | Ken |
| 11 | glee | Ginny | Lee |
| 12 | nwatts | Naomi | Watts |
| 13 | jwong | Jin | Wong |
| 14 | syin | Shen | Yin |
+--------+-----------------+------------------+----------------+
USERS_META
+--------+--------+-----------------+------------------+
| ID | UID | meta_key | meta_value |
+--------+--------+-----------------+------------------+
| 1 | 2 | business_name | Company Inc. |
| 2 | 2 | city | New York |
| 3 | 2 | state | NY |
| 5 | 9 | city | Boston |
| 6 | 9 | state | MA |
| 7 | 11 | business_type | Printer |
| 8 | 8 | chamber_member | true |
| 9 | 2 | business_type | Design |
+--------+--------+-----------------+------------------+
Below is an example of what I'd like to return:
USERS
+--------+-----------------+------------+------------+------------------+
| ID | username | city | state | business_name |
+--------+-----------------+------------+------------+------------------+
| 2 | hthompson | New York | NY | Company Inc. |
+--------+-----------------+------------+------------+------------------+
OR
$user['ID'] = 2
$user['username'] = hthompson
$user['city'] = New York
$user['state'] = NY
$user['business_name'] = Company Inc.
The closest I've come is this:
$query = ("SELECT *
FROM users
INNER JOIN users_meta ON users.ID = users_meta.UID
WHERE
users_meta.meta_key = 'city' OR
users_meta.meta_key = 'state' OR
users_meta.meta_key = 'business_name'
");
However, doing such returns three results for each unique user ID, and I'm aiming to returning one with all the meta info specified. The primary purpose of this is so that I will be able to search using a keyword, which would apply to the USERS.first_name, USERS.first_name and USERS_META.business_name columns and then obviously return results in a table showing ID, Business Name, City, State, First & Last Name.
Thanks in advance!

You can try this:
SELECT
u.ID,
u.username,
m0.meta_value as city,
m1.meta_value as state,
m2.meta_value as business_name
FROM
users u,
users_meta m0,
users_meta m1,
users_meta m2
WHERE
u.ID = m0.UID
AND m0.meta_key = 'city'
AND u.ID = m1.UID
AND m1.meta_key = 'state'
AND u.ID = m2.UID
AND m2.meta_key = 'business'

As far as getting the information out I would just suggest joining the table together and using php to make the array. Something similar to this:
<?php
//if search is blank, returns all rows
$search = isset($_POST['search'])?mysql_real_escape_string($_POST['search']):'';
//query for all rows with meta key/values including extra
//rows from the join. extra rows will be taken out later.
$result = mysql_query(
"SELECT
U.ID,
U.USERNAME,
U.FIRST_NAME,
U.LAST_NAME,
UM.META_KEY,
UM.META_VALUE
FROM USERS U
JOIN USERS_META UM ON U.ID=UM.UID
WHERE
UM.META_KEY IN ('city', 'state', 'business_name')
AND U.FIRST_NAME LIKE '%{$search}%'");
//an empty array to put our results into
$out = array();
//loop through the rows
while($row=mysql_fetch_assoc($out)){
//check if the user id has been added already
if(!isset($out[$row['ID']])){
//if not, add it with generic information
$out[$row['ID']] = array(
'ID'=>$row['ID'],
'USERNAME'=>$row['USERNAME'],
'FIRST_NAME'=>$row['FIRST_NAME'],
'LAST_NAME'=>$row['LAST_NAME']);
}
//add the meta key and value
$out[$row['ID']][$row['META_KEY']] = $row['META_VALUE'];
}
//display
echo '<pre>'.print_r($out,1).'</pre>';
?>

Related

How to SELECT 2 joined tables in one MySQL query?

I have 1 master_table and 2 sub_tables. I want the join the 3 columns together (but the problem is the 2 sub_tables do not have any column that share the same value) and then SELECT * based on 2 different columns from the 2 sub_tables.
I've searched and tried many ways of coding, but couldn't find a solution.
SELECT *
FROM (master INNER JOIN sub_1 ON master.id=sub_1.id WHERE sub_1.column_1 = 'Y')
AND (master INNER JOIN sub_2 ON master.id=sub_2.id WHERE sub_2.column_2 = 'Y')
ORDER BY master.id
++++++++++++++++++++++++++++++++++++++++++++++++++
* Finally, solved. See the solution at the bottom of this post. *
++++++++++++++++++++++++++++++++++++++++++++++++++
===========
Edit: explain more about my data, problem and MySQL code
I have 3 tables stored in MySQL as follow
Master_table: regist
------------------------------------------
| reg_no | firstname | lastname | submit |
------------------------------------------
| 1 | first_A | last_A | N |
| 2 | first_B | last_B | A |
| 3 | first_C | last_C | P |
| 4 | first_D | last_D | P |
| 5 | first_E | last_E | A |
| 6 | first_F | last_F | N |
| 7 | first_G | last_G | N |
| 8 | first_H | last_H | A |
------------------------------------------
Sub_1: sub_A Sub_2: sub_P
------------------------------ ------------------------------
| reg_no | A_title | reply_A | | reg_no | P_title | reply_P |
------------------------------ ------------------------------
| 2 | 222 | Y | | 3 | 333 | N |
| 5 | 555 | N | | 4 | 444 | Y |
| 8 | 888 | Y | ------------------------------
------------------------------
I want to create a query that gives result like this
----------------------------------------------------------------------------------
| reg_no | firstname | lastname | submit | A_title | reply_A | P_title | reply_P |
----------------------------------------------------------------------------------
| 2 | first_B | last_B | A | 222 | Y | | |
| 8 | first_H | last_H | A | 888 | Y | | |
| 4 | first_D | last_D | P | | | 444 | Y |
----------------------------------------------------------------------------------
or
-----------------------------------------------------------
| reg_no | firstname | lastname | submit | title | reply |
-----------------------------------------------------------
| 2 | first_B | last_B | A | 222 | Y |
| 8 | first_H | last_H | A | 888 | Y |
| 4 | first_D | last_D | P | 444 | Y |
-----------------------------------------------------------
$sql = "SELECT *
FROM (regist INNER JOIN sub_A ON regist.reg_no = sub_A.reg_no WHERE sub_A.reply_A = 'Y')
AND (regist INNER JOIN sub_P ON regist.reg_no = sub_P.reg_no WHERE sub_P.reply_P = 'Y')
ORDER BY regist.reg_no";
Expected outcome:
ECHO personal data of all registrants who got reply as 'Y'
if($row['submit']=="A") $title = $row['A_title'];
elseif($row['submit']=="P") $title = $row['P_title'];
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['reg_no']." / ".$row['firstname']." ".$row['lastname']." / ".$title."<br>";
}
Problem: my SELECT code resulted in error. The code from #GMB and #Rogue didn't error, but echo give nothing.
If it is not possible to code a query as I want, I will just modify the column names (sub_1.reply_A and sub_2.reply_P) to be the same and change the input code in other webpages. However, it would be best if there is a way because I don't know whether the 'reply' columns were used somewhere else.
========================
Solution: a little modification from #Rogue code
SELECT *
FROM master
LEFT OUTER JOIN sub_1
ON master.id=sub_1.id
LEFT OUTER JOIN sub_2
ON master.id=sub_2.id
WHERE sub_1.column_1 = 'Y'
OR sub_2.column_2 = 'Y'
ORDER BY master.id
Do you just want simple JOINs between these 3 tables ?
SELECT m.*, s1.*, s2.*
FROM master m
INNER JOIN sub_1 s1 ON m.id=s1.id AND s1.column_1 = 'Y'
INNER JOIN sub_2 s2 ON m.id=s2.id AND s2.column_2 = 'Y'
ORDER BY m.id;
If you have master records that may not exist in both sub tables, you can switch to LEFT JOIN to avoid filtering them out.
Guidelines :
typical syntax is SELECT ... FROM table1 INNER JOIN table2 ON ... INNER JOIN table3 ON...
better put all conditions related to a JOINed table in the ON clause of the join rather than in the WHERE clause
avoid SELECT * : be specific about the columns you want to select
use table aliases to make the query easier to read
You're a little off syntactically:
SELECT *
FROM master
LEFT OUTER JOIN sub_1
ON master.id=sub_1.id
LEFT OUTER JOIN sub_2
ON master.id=sub_2.id
WHERE sub_1.column_1 = 'Y'
AND sub_2.column_2 = 'Y'
ORDER BY master.id
Personally I would recommend not using SELECT * and only grabbing the data you will need. As for determining what join to use, I like to link to CodingHorror's blog post in these times.
Edit: swapped INNER to LEFT OUTER, per OP's update

PHP SQL - Retrieve shared values from a another table not as expected

I'm needing to retrieve shared values from a table based on a value from another table, but don't show duplicates.
Example of what tables I have...
Table - members
+-----------------+
| ID | NAME |
+-----------------+
| 1 | Bob |
| 2 | Jack |
| 3 | Jane |
| 4 | Bruce |
| 5 | Clark |
| 6 | Peter |
+-----------------+
Table - groups
+--------------------------------+
| ID | NAME | MANAGER_ID |
+--------------------------------+
| 1 | Group A | 1 | (Bob)
| 2 | Group B | 2 | (Jack)
| 3 | Group C | 1 | (Bob)
+--------------------------------+
Table - group_members
+--------------------------------+
| ID | GROUP_ID | MEMBER_ID |
+--------------------------------+
| 1 | 1 | 3 | (Group A - Jane)
| 2 | 1 | 4 | (Group A - Bruce)
| 3 | 1 | 5 | (Group A - Clark)
| 4 | 1 | 6 | (Group A - Peter)
| 5 | 2 | 3 | (Group B - Jane)
| 6 | 3 | 4 | (Group B - Bruce)
| 7 | 3 | 5 | (Group C - Clark)
+--------------------------------+
What I am needing
(Note: I'm using * in queries here to shorten code.)
If 'Bob' sees all his groups.
Look at 'group_members' table and show all members that belong to it...
$q = SELECT * FROM groups WHERE manager_id = $id;
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch-assoc($r) {
$q2 = SELECT *, count(MEMBERS_ID) AS group_count FROM group_members LEFT JOIN members ON group_members.MEMBER_ID = members.id WHERE group_id = '$row[GROUP_ID]';
$r2 = mysqli_query($dbc, $q2);
while ($row2 = mysqli_fetch-assoc($r2) {
echo $row2['name'];
}
}
This shows me the list as expected.
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| Jane | 1 |
| Bruce | 1 |
| Clark | 1 |
| Peter | 1 |
| Bruce | 1 |
| Clark | 1 |
+------------------------+
I Add GROUP BY group_members.group_id to my 2nd query and that shows.
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| Jane | 1 |
| Bruce | 2 |
| Clark | 2 |
| Peter | 1 |
+------------------------+
Which is perfect... But here is the problem
if I add a WHERE members.name LIKE \'%clark%\' then it outputs...
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| | |
| | |
| Clark | 1 |
| | |
| | |
| Clark | 1 |
+------------------------+
It ignores GROUP BY and shows blank rows where other entries would show.
So with all that said. Does any one know why or a better way to do this please?
Been at it for a while now and would really appreciate any assistance.
EDITED:
Here's the full query with all the columns used:
$q = SELECT * FROM groups WHERE manager_id = $id;
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch-assoc($r) {
$q2 = SELECT members.id) AS memid, members.first, members.last, members.comname, members.email, members.sector, (members.status) AS memstatus, (group_members.id) AS groupid, (group_members.member_id) AS memidgroup, group_members.group_id, COUNT(group_members.member_id) AS groupcount, member_roles.role FROM members LEFT JOIN group_members ON members.id = group_members.member_id LEFT JOIN member_roles ON members.role_id = member_roles.id WHERE group_id = '$row[GROUP_ID]' AND members.name LIKE '%clark%' GROUP BY group_members.group_id;
$r2 = mysqli_query($dbc, $q2);
while ($row2 = mysqli_fetch-assoc($r2) {
echo $row2['name'];
}
}
Your query or problem is not completely stated. One cannot guess or assume.
Post your last query as well as all queries dont worry about saving the space.
Those blank rows have data that why they are in the table.
Base on your explanation or your query, here is my simple answer
SELECT id,
(select groups.id from groups where groups.id = group_members.group_id )AS group_members_id,
(select groups.name from groups where groups.id = group_members.group_id )AS group_members_name,
(select members.id from members where members.id = group_members.member_id )AS members_id,
(select members.name from members where members.id = group_members.member_id )AS members_name,
count((select members.id from members where members.id = group_members.member_id ) )as members_id_count FROM group_members WHERE (select members.name from members where members.id = group_members.member_id ) LIKE '%clark%' group by members_id
As you mentioned
WHERE members.name LIKE \'%clark%\'
you were selecting data from the members table whereas you have to select the data from group_members table.

MySQL join, return 1 row from one table and multiple rows from another table as an array or list

I am working on a project to catalogue laptops and as such am trying to re-use as much information as possible. A simplified version of the MySQL tables are:
Table: laptop
|----------------------------------|
| id | make | line | model |
| 1 | 1 | 1 | Late 2015 13" |
|----------------------------------|
Table: make
|----------------------------------|
| id | name | other info |
| 1 | Apple | |
|----------------------------------|
Table: line
|----------------------------------|
| id | name | other info |
| 1 | MacBook Pro | |
|----------------------------------|
Table: networking
|----------------------------------|
| id | name | other info |
| 1 | A wifi card | |
| 2 | Another card | |
| 3 | Yet another | |
|----------------------------------|
Table: laptop_networking
|----------------------------------|
| id | networking | laptop |
| 1 | 3 | 1 |
| 2 | 1 | 1 |
|----------------------------------|
So far I used the current statement to retrieve the data in PHP
$statement = $dbc->prepare("
SELECT l.id
, m.id AS makeID
, m.name AS makeName
, n.id AS lineID
, n.name AS lineName
, l.model
FROM laptop l
JOIN make m
ON l.make = m.id
JOIN line n
ON l.line = n.id
WHERE l.id = :laptop);
$statement->bindParam(':laptop', $anID, PDO::PARAM_INT);
$statement->execute();
$theLaptop = $statement0>fetch();
At present running this code with $anID = 1 returns
|---------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | Model |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" |
|---------------------------------------------------------------|
What I would like to do is append another column to the table which returns all names from Networking which have an ID equal to a row in laptop_networking where the laptop field is equal to the ID from the retrieved laptop row
Such as:
|------------------------------------------------------------------------------------------|
| id | makeID | makeName | lineID | lineName | model | networking |
| 1 | 1 | Apple | 1 | MacBook Pro | Late 2015 13" | Yet another, A wifi card |
|------------------------------------------------------------------------------------------|
Is this possible as my many attempts at different types of JOINs have not yielded the desired results.
Thank you
Try this query:
SELECT laptop.id,
make.id AS makeID,
make.name AS makeName,
line.id AS lineID,
line.name AS lineName,
laptop.model,
t.networking
FROM laptop
INNER JOIN make
ON laptop.make = make.id
INNER JOIN line
ON laptop.line = line.id
INNER JOIN
(
SELECT t1.laptop, GROUP_CONCAT(t2.name) AS networking
FROM laptop_networking t1
INNER JOIN networking t2
ON t1.networking = t2.id
GROUP BY t1.laptop
) t
ON laptop.id = t.laptop
WHERE laptop.id = :laptop
Demo here:
Rextester

Display rows based on sql results

I am using caldera forms in my WordPress site to collect data for new admissions for our club. Form functions as expected. I am trying to view a list of open applications and a page to view them. Following is my SQL table tor entries (cf_form_entries).
+----+-----------------+--------+
| ID | Form ID | Status |
+----+-----------------+--------+
| 1 | CF5852c23e56b1d | active |
+----+-----------------+--------+
| 2 | CF5852c23e56b1d | active |
+----+-----------------+--------+
| 3 | CF5852c23e56b1d | active |
+----+-----------------+--------+
Following table contains all the information submitted by the form (cf_form_entry_values);
+----+----------+---------------+--------------------+
| id | entry_id | slug | value |
+----+----------+---------------+--------------------+
| 1 | 1 | branch | Branch A |
| 2 | 1 | full_name | asdasd asdasd |
| 3 | 1 | email_address | b2196363#trbvn.com |
| 4 | 1 | phone | 111111111 |
| 5 | 2 | branch | Branch A |
| 6 | 2 | full_name | Full Name |
| 7 | 2 | email_address | asdasd#asdas.com |
| 8 | 2 | phone | 111111111 |
| 9 | 3 | branch | Branch A |
| 10 | 3 | full_name | Namwe |
| 11 | 3 | email_address | wert#wertwert.com |
| 12 | 3 | phone | 111111111 |
+----+----------+---------------+--------------------+
I can run a simple select query and get the open application details of a given branch, inner joining tables.
SELECT cf_form_entries.id,
cf_form_entries.form_id,
cf_form_entries.status,
cf_form_entry_values.slug,
cf_form_entry_values.value
FROM cf_form_entry_values
INNER JOIN cf_form_entries
ON cf_form_entry_values.entry_id = cf_form_entries.id
WHERE cf_form_entry_values.slug = 'branch'
AND cf_form_entry_values.value LIKE '%Branch A%'
Above query results in the following table;
+----+-----------------+--------+--------+----------+
| id | form_id | status | slug | value |
+----+-----------------+--------+--------+----------+
| 1 | CF5852c23e56b1d | active | branch | Branch A |
| 3 | CF5852c23e56b1d | active | branch | Branch A |
+----+-----------------+--------+--------+----------+
My question is, How can I display (echo) the other details such as the name, email address, etc. of the selected tables?
As such my end result shall display all details of the open applications in a table. (not just the branch name)
I tried a while loop. But I can only echo the branch names as they are the only data selected in my inner joined table.
One method is conditional aggregation:
SELECT fe.id, fe.form_id, fe.status,
MAX(CASE WHEN fev.slug = 'branch' THEN fev.value END) as branch,
MAX(CASE WHEN fev.slug = 'full_name' THEN fev.value END) as full_name,
. . .
FROM cf_form_entries fe INNER JOIN
cf_form_entry_values fev
ON fev.entry_id = fe.id
GROUP BY fe.id, fe.form_id, fe.status;
The nice thing about this approach is that adding a new value only requires adding a new expression in the SELECT.
Try Following Query By Using LEFT JOIN ON Two Tables.
SELECT cfev.*,cfm.Form ID as entry_id
FROM cf_form_entry_values cfev
LEFT JOIN cf_form_entries cfm ON cfm.id = cfev.entry_id
WHERE cfev .slug = 'branch' AND vfm.value LIKE '%Branch A%'
This Might Be Helpful. And You Get Proper Output...
This should give you the first two values, and you can use the same pattern for the rest:
SELECT entries.id,
entries.form_id,
entries.status,
(SELECT value FROM cf_form_entry_values as v
WHERE slug='branch' and entry_id=entries.entry_id) as branch,
(SELECT value FROM cf_form_entry_values as v
WHERE slug='full_name' and entry_id=entries.entry_id) as full_name
FROM cf_form_entry_values
INNER JOIN (
SELECT * FROM cf_form_entry_values
INNER JOIN cf_form_entries
ON cf_form_entry_values.entry_id = cf_form_entries.id
WHERE cf_form_entry_values.slug = 'branch'
AND cf_form_entry_values.value LIKE '%Branch A%'
) as entries
ON cf_form_entry_values.entry_id = entries.id
GROUP BY cf_form_entries.id

MySql query on two table

I have two table 'users' and 'friends' I am having difficulty joining them
users table
id | name | usercode
--------------------
1 | david | 2WM
2 | Samme | E5N
3 | Awudu | C0Q
4 | John | VX6
5 | Jerem | FG3
Friends Table
id | actor | target
--------------------
1 | E5N | FG3
2 | 2WM | VX6
3 | FG3 | 2WM
4 | C0Q | VX6
5 | FG3 | VX6
Basically i want to select all users from USERS table who has 'FG3' in either target or actor column in the FRIENDS table.
The result will be
id | name | usercode | actor | target
--------------------------------------
2 | Samme | E5N | E5N | FG3
1 | david | 2WM | FG3 | 2WM
5 | John | VX6 | FG3 | VX6
I have triend everything i know but still i am not getting the correct results
I will be glad if anyone can help me since I need to present this work tomorrow morning. Thank you
Looks like you want to join on usercode equals actor or target, then put the 'FG3' part in a WHERE clause:
SELECT users.id, users.name, users.usercode, friends.actor, friends.target
FROM users
INNER JOIN friends
ON users.usercode = friends.actor OR users.usercode = friends.target
WHERE users.usercode != 'FG3'
AND (friends.actor = 'FG3' OR friends.target = 'FG3');
Using INNER JOIN limits your query to only records that exist in both tables.

Categories