populate mysql table on the basis of another - php

I have 3 mysql tables containing a few fields. Please refer to the following
-------- -------- --------
table 1 | table 2 | table 3
-------- -------- --------
a_id | b_id | email
| a_id
name | status | b_id
email_1 | date | name
phone | ref | phone
address | email_2 | address
state | from | state
| status
| date
| ref
| from
The email_1 and email_2 is exactly same.
I need to populate the table3 fields with all table1 and table2 data. But I need to store them in one row based on email. So they look like following:
=================================================================================
table 3
=================================================================================
email | a_id | b_id | name | phone | address | state | status | date | ref | from
------+------+------+------+-------+---------+-------+--------+------+-----+-----
a#x.co| 9 | 112 | John | 999 | xxxx | NY | 0 | 15Jue| dave| y
------+------+------+------+-------+---------+-------+--------+------+-----+-----
b#x.co| 6 | 338 | Sue | 909 | xxxx | NY | 1 | 12Jue| kell| z
------+------+------+------+-------+---------+-------+--------+------+-----+-----
c#x.co| 3 | 152 | John | 679 | xxxx | NY | 1 | 10Jue| lois| g
------+------+------+------+-------+---------+-------+--------+------+-----+-----
d#x.co| 8 | 145 | John | 599 | xxxx | NY | 0 | 8Jue | sue | f
I can't figure it out how to do that. I'm using core php, mysql. Any help please?
Thanks!

I would use something like this for mysql:
insert into table_3
(
`email`,
`a_id`,
`b_id`,
`name`,
`phone`,
`address`,
`state`,
`status`,
`date`,
`ref`,
`from`
)
select
`a`.`email_1`,
`a`.`a_id`,
`b`.`b_id`,
`a`.`name`,
`a`.`phone`,
`a`.`address`,
`a`.`state`,
`b`.`status`,
`b`.`date`,
`b`.`ref`,
`b`.`from`
from
table_1 as `a`
inner join
table_2 as `b` on `a`.`email_1` = `b`.`email_2`
But you should probably go read up on MySQL insert syntax to see it's power, and on joining data :)

insert into table_3(`email`,`a_id`,`b_id`,`name`,`phone`,`address`,`state`,`status`,`date`,`ref`,`from`)
select `email_1`,`a_id`,`b_id`,`name`,`phone`,`address`,`state`,`status`,`date`,`ref`,`from`
from table_1,table_2
where email_1=email_2;

Related

how do I join multiple tables with foreign key constraints

I am a newbie to mysql, and originally I was going to create an enum datatype for my table but I found this question Create enum in SQL Server, and used it as a reference as that is what I needed. However when I tried to grab the data using the following sql statement it failed:
$sql = "
SELECT users.userID
, users.firstName
, users.lastName
, membersrank.rank
, memberstyle.style
FROM users
JOIN membersrank
ON membersrank.rankID = memberships.rankID
JOIN memberstyle
ON memberstyle.styleID = memberships.styleID
JOIN memberships
ON users.userID = memberships.userID
";
The prepare statement failed when I ran it. I assumed something is wrong with the sql statement.
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("location: /index.php?error=stmtFailed");
exit();
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
These two tables below are the "user_rank" table referenced from the link.
Table: membersrank Table: memberstyle
| rankID | rank | | styleID | style |
| -------- | -------- | | -------- | ------------ |
| 0 | Guest | | 0 | N/A |
| 1 | Member | | 1 | Casual |
| 2 | Admin | | 2 | Competitive |
Table: memberships (is it the table, 'users', from the link)
| membershipID | userID | rankID | styleID |
| ------------ | -------- | -------- | -------- |
| 0 | 1 | 1 | 1 |
| 1 | 2 | 2 | 1 |
| 2 | 3 | 1 | 0 |
Result im trying to achieve:
| userID | firstName | lastName | rank | style |
| ------------ | ---------- | -------- | -------- | -------- |
| 0 | John | Doe | Member | Casual |
| 1 | Jane | Doe | Admin | Casual |
| 2 | Joe | Smith | Member | N/A |
How do I go about this and what is the proper sql statement?
(if need the unlisted table 'users' is required as info then is as you see in the my result table without the rank and style columns.)
Thanks in advance!

Select distinct rows order by highest values

I have a table like
Name | Image | Points | Country
-------------------------------
Bob | a.jpg | 100 | USA
Bob | b.jpg | 56 | USA
Sal | c.jpg | 87 | UK
Jim | d.jpg | 34 | UK
Bet | e.jpg | 23 | USA
Bren | f.jpg | 5 | USA
Bren | g.jpg | 15 | UK
Test | h.jpg | 10 | USA
I want to get the top 4 highest rows based on the "Points" column where the country is "USA" and removing duplicate "Names", so the desired outcome would be
Name | Image | Points | Country
-------------------------------
Bob | a.jpg | 100 | USA
Bet | e.jpg | 23 | USA
Test | h.jpg | 10 | USA
Bren | f.jpg | 5 | USA
Any help would be appreciated thank you
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(image VARCHAR(12) NOT NULL PRIMARY KEY
,name VARCHAR(12) NOT NULL
,points INT NOT NULL
,country VARCHAR(12) NOT NULL
);
INSERT INTO my_table VALUES
('a.jpg','Bob' ,100,'USA'),
('b.jpg','Bob' , 56,'USA'),
('c.jpg','Sal' , 87,'UK'),
('d.jpg','Jim' , 34,'UK'),
('e.jpg','Bet' , 23,'USA'),
('f.jpg','Bren', 5,'USA'),
('g.jpg','Bren', 15,'UK'),
('h.jpg','Test', 10,'USA');
SELECT a.*
FROM my_table a
JOIN
( SELECT name,MAX(points) points FROM my_table WHERE country = 'USA' GROUP BY name ) b
ON b.name = a.name
AND b.points = a.points
ORDER
BY points DESC
LIMIT 4;
+-------+------+--------+---------+
| image | name | points | country |
+-------+------+--------+---------+
| a.jpg | Bob | 100 | USA |
| e.jpg | Bet | 23 | USA |
| h.jpg | Test | 10 | USA |
| f.jpg | Bren | 5 | USA |
+-------+------+--------+---------+
select table.* from table join
(select Name, max(Points) mp from table where Country='USA' group by Name
order by mp desc limit 4) t
on table.Name = t.Name and table.Points = t.mp and table.Country='USA'
order by table.points desc
When a person's max point row have two record, eg bob's b.jpg is also 100, this would lead to multi rows in bobs result.
Try This:
SELECT Name,Image,MAX(points),country
FROM table_1
ORDER BY points desc
GROUP BY Name,points
LIMIT 4

MySQL: linking tables with extracted sum of column per row

I have 3 tables:
MySQL: I need to link these tables and extracted sum of one of the column per row in the resulting table
tblRedemption
+---------------------+
| OrderID | OrderDesc |
+---------------------+
| 1000001 | aaaa |
| 1000002 | bbbb |
| 1000003 | cccc |
| 1000004 | dddd |
+---------------------+
tblLink
+------------------------+
| SubmissionID | OrderID |
+------------------------+
| 201 | 1000001 |
| 202 | 1000002 |
| 203 | 1000003 |
| 204 | 1000004 |
+------------------------+
tblSubmissions
+-------------------------------------------+
| SubmissionID | Name | Mobile | Amount |
+-------------------------------------------+
| 150 | Amy | 1111111111 | 10 |
| 200 | Bob | 2222222222 | 20 |
| 201 | Carl | 3333333333 | 30 |
| 202 | Dave | 4444444444 | 10 |
| 203 | Carl | 3333333333 | 25 |
| 204 | Fin | 5555555555 | 35 |
+-------------------------------------------+
Expected Results:
+---------------------------------------------------------------------+
| SubmissionID | Name | mobile | OrderDesc | Amount | TotalAmount |
+---------------------------------------------------------------------+
| 201 | Carl | 3333333333 | aaaa | 30 | 55 |
| 203 | Carl | 3333333333 | bbbb | 25 | 55 |
| 204 | Fin | 5555555555 | cccc | 35 | 35 |
| 202 | Dave | 4444444444 | dddd | 10 | 10 |
+---------------------------------------------------------------------+
Number of tblSubmission is a bigger list than the tblredemption.
There are customers with multiple entries tblSubmission identified by their mobile (see Carl).
The table tbLink joins the 2 tblSubmission and tblRdemption.
The resulting table also needs a new column which holds the total amount for each particular customer (by mobile).
The expected results needs to include:
The SubmissionID and OrderDesc from the "tblRedemption" table.
The Name, Mobile and Amount from the tblSubmissions table.
All my queries ether gives me a small subset or just one row, or "multiple rows returned".
Any ideas?
Try this:
select l.submissionid, s.name, s.mobile, s.amount, t.totalamount
from tbllink l
inner join tblsubmissions s on l.submissionid = s.submissionid
inner join (
select `name`, sum(amount) as totalamount
from tblsubmissions
group by `name`
) t on s.`name` = t.`name`
Example: http://sqlfiddle.com/#!9/2ea56a/5
Same query totalled by mobile number
select l.submissionid, s.name, s.mobile, s.amount, t.totalamount
from tbllink l
inner join tblsubmissions s on l.submissionid = s.submissionid
inner join (
select mobile, sum(amount) as totalamount
from tblsubmissions
group by mobile
) t on s.mobile = t.mobile
EDIT:
Including order desc is relatively easy also. Let's see:
select l.submissionid, s.name, s.mobile, r.orderdesc, s.amount, t.totalamount
from tbllink l
inner join tblredemption r on l.orderid = r.orderid
inner join tblsubmissions s on l.submissionid = s.submissionid
inner join (
select `name`, sum(amount) as totalamount
from tblsubmissions
group by `name`
) t on s.`name` = t.`name`
Example: http://sqlfiddle.com/#!9/63540/2
Tables
create table tblredemption (orderid int, orderdesc varchar(100));
insert into tblredemption values (1000001, 'aaaa'), (1000002, 'bbbb'), (1000003, 'cccc'), (1000004, 'dddd');
create table tbllink (submissionid int, orderid int);
insert into tbllink values (201,1000001), (202,1000002), (203,1000003), (204,1000004);
create table tblsubmissions (
submissionid int,
`name` varchar(20),
mobile varchar(20),
amount int
);
insert into tblsubmissions values
( 150 , 'Amy' , '1111111111', 10 ),
( 200 , 'Bob' , '2222222222' , 20 ),
( 201 , 'Carl' , '3333333333' , 30 ),
( 202 , 'Dave' , '4444444444' , 10 ),
( 203 , 'Carl' , '3333333333' , 25 ),
( 204 , 'Fin' , '5555555555' , 35 );
Results:
| submissionid | name | mobile | orderdesc | amount | totalamount |
|--------------|------|------------|-----------|--------|-------------|
| 201 | Carl | 3333333333 | aaaa | 30 | 55 |
| 203 | Carl | 3333333333 | cccc | 25 | 55 |
| 202 | Dave | 4444444444 | bbbb | 10 | 10 |
| 204 | Fin | 5555555555 | dddd | 35 | 35 |

Complicated mySQL query in php page

If you have seen my previous requests you will see I am a TOTAL NOOB with php and mySQL. I wish I wasn't even doing this but I have been dumped in the deep end by people that have let me down. It is 1 day away from "completion" and I am left to pick up and mend the pieces of this system I have which doesn't fully function!
I have tried to explain this as logically and clearly as possible. If you need clarification please let me know and I will do my best!
Thanks in advance for any help as I am now desperate to get this thing done!
I have 3 issues!
ISSUE1
Matching Keys
(x)
TABLE1
| C_ID | C_Eth_O (x) |
+--------------------+-------------------------+
| 234 | 8 |
| 341 | 11 |
| 440 | 2 |
TABLE2
| Eth_ID (x) | C1_Eth_O |
+-----------------------+------------------------+
| 2 | Label2 |
| 8 | Label8 |
| 9 | Label9 |
| 11 | Label11 |
I need to list all the "C1_Eth_O" values in a multi select list. The user will make multiple selections from that list. When submitted I need to get the "Eth_ID" value(s) and return all the value(s) from TABLE1 where any of the selected options "C_Eth_O" = "Eth_ID". Each "C_ID" can only have one "C_Eth_O".
ISSUE2
Matching Keys
(x)
(o)
TABLE1
| C_ID (x) |
+---------------------+
| 234 |
| 341 |
| 440 |
TABLE3
| Ail_ID (o) | Ali_Label |
+-------------------------+-------------------------+
| 1 | Label1 |
| 2 | Label2 |
| 3 | Label3 |
| 4 | Label4 |
| 5 | Label5 |
| 6 | Label6 |
TABLE4
| CA_ID | C1_ID (x) | Ail1_ID (o) |
+---------------------+------------------------+------------------------+
| 1 | 234 | 1 |
| 2 | 341 | 4 |
| 3 | 341 | 6 |
| 4 | 440 | 2 |
I need to list all the "Ali_Label" values from TABLE3 in a multi select list. The user will make multiple selections from that list. When submitted I need to get the "Ail_ID" value(s) from TABLE3 and return all the value(s) from TABLE1 where any of the selected match in TABLE4 "Ali1_ID" = "Ail_ID" & "C1_ID" = "C_ID". Each "C_ID" can have multiple "Ail_ID" values
ISSUE3
Matching Keys
(x)
(o)
(-)
TABLE1
| C_ID (x) |
+---------------------+
| 234 |
| 341 |
| 440 |
TABLE3
| Ail_ID (o) | Ali_Label |
+------------------------+-------------------------+
| 1 | Label1 |
| 2 | Label2 |
| 3 | Label3 |
| 4 | Label4 |
| 5 | Label5 |
| 6 | Label6 |
TABLE5
| R_ID | C1_ID (x) | Cf1_ID (-) |
+-----------------------+-----------------------+-----------------------+
| 1 | 234 | 768 |
| 2 | 234 | 854 |
| 3 | 234 | 768 |
| 4 | 440 | 854 |
TABLE6
| CA_ID | Cf_ID (-) | Ail1_ID (o) |
+---------------------+------------------------+------------------------+
| 1 | 768 | 1 |
| 2 | 854 | 4 |
| 3 | 768 | 6 |
| 4 | 880 | 2 |
I need to list all the "Ali_Label" values from TABLE3 in a multi select list. The user will make multiple selections from that list. When submitted I need to get the "Ail_ID" value(s) from TABLE3 and return all the value(s) from TABLE1 where any of the selected "Ali_ID" = "Ail1_ID" & "C1_ID" = "C_ID" & "Cf1_ID" = "Cf_ID". Each "C_ID" can have multiple "Cf1_ID" values AND each "Cf_ID" can have multiple "Ail1_ID" values.
I have the system working returning simple queries such as
SELECT * FROM table1 WHERE C_ID = 234
but nothing with multiple tables and multiple results per C_ID!
Thanks again!
ISSUE 1 -
SELECT * FROM table1 INNER JOIN table 2 ON table1.C_Eth_O = table2.Eth_ID
ISSUE 2 -
SELECT * FROM table1 INNER JOIN table4 ON table1.C_ID = table4.C1_ID INNER JOIN table3 ON table3.Ail_ID = table4.Ail1_ID
ISSUE 3 -
SELECT * FROM table1 INNER JOIN table5 ON table1.C_ID = table5.C1_ID INNER JOIN table6 ON table5.Cf1_ID = table6.Cf_ID INNER JOIN table3 ON table3.Ail_ID = table6.Ail1_ID

MySQL query to get data from 5 tables?

What is the right MySQL query for this? Here's what I want to achieve.
I would like to display all status update entries, date posted, the
poster username, gender, city, and tags
I would like to display all status update entries by a member with user_id='1', the date the status update was posted, the poster username, gender, city, and tags that member has on his profile
And how can I display all the tags that the user have on their profile, in one line separated by ','? I tried group_concat earlier but i couldn't make it work. please help.
Here's my tables
STATUS_UPDATE Table
+------------------------------------------------------+
| status_id | user_id | body | postdate |
+-----------+---------+-----------------+--------------+
| 1 | 1 | hello world | Aug 12, 2012 |
+-----------+---------+-----------------+--------------+
| 2 | 1 | i miss you | Aug 13, 2012 |
+-----------+---------+-----------------+--------------+
| 3 | 2 | lorem ipsum | Aug 14, 2012 |
+-----------+---------+-----------------+--------------+
| 4 | 2 | why me? why? | Aug 14, 2012 |
+-----------+---------+-----------------+--------------+
MEMBERS Table //Primary data of members
+---------------------------------------------------+
| user_id | username | password | email |
+---------+----------+------------+-----------------+
| 1 | john_doe | qwerty | john#doe.com |
+---------+----------+------------+-----------------+
| 2 | maryjane | pass123 | mary#jane.com |
+---------+----------+------------+-----------------+
MEMBERS_DATA Table //Profile Fields
+----------------------------------------------+
| user_id | gender | description | city |
+---------+--------+---------------+-----------+
| 1 | male | i am simple | chicago |
+---------+--------+---------------+-----------+
| 2 | female | i am flirty | newyork |
+---------+--------+---------------+-----------+
MEMBERS_TAGS Table //tags that members added to their profiles
+-------------------+
| user_id | item_id |
+---------+---------+
| 1 | 555 |
+---------+---------+
| 1 | 666 |
+---------+---------+
| 1 | 7777 |
+---------+---------+
| 2 | 8888 |
+---------+---------+
TAGS Table //the info of the tags
+------------------------------+
| item_id | cat_id | name |
+---------+--------+-----------+
| 555 | 5 | sexy |
+---------+--------+-----------+
| 666 | 5 | beauty |
+---------+--------+-----------+
| 7777 | 6 | music |
+---------+--------+-----------+
| 8888 | 6 | movies |
+---------+--------+-----------+
CATEGORY Table //the category of the tags
+-------------------------+
| cat_id | category_name |
+---------+---------------+
| 5 | appearance |
+---------+---------------+
| 6 | hobbies |
+---------+---------------+
BTW I'm coding in PHP, I want to thank you in advance for the help.
SELECT
STATUS_UPDATE.* ,
MEMBERS.username ,
MEMBERS_DATA.gender ,
MEMBERS_DATA.city
TAGS.*
FROM UPDATE
LEFT JOIN MEMBERS ON MEMBERS.user_id = STATUS_UPDATE.user_id
LEFT JOIN MEMBERS_DATA ON MEMBERS_DATA.user_id = STATUS_UPDATE.user_id
LEFT JOIN MEMBERS_TAGS ON MEMBERS_TAGS.user_id = STATUS_UPDATE.user_id
LEFT JOIN TAGS ON TAGS.item_id = MEMBERS_TAGS.item_id

Categories