Subquery using the same table - mysql

I need to make a subquery in the same table to bring me back all the results inside of each id, and print it inside on a while.
$stl = $conn->prepare("SELECT DISTINCT CONCAT(first_name,' ',last_name) AS name, rol FROM USERS WHERE id = :id AND rol = 1 ORDER BY id ASC");
$stl->bindParam(':id', $id, PDO::PARAM_INT);
$stl->execute();
echo '<table><thead><tr><th>MASTER</th><th>SUPERVISOR</th><th>NOOB</th></thead>';
echo '<tbody>';
while($row = $stl->fetch(PDO::FETCH_ASSOC)) { ?>
echo '<tr><td>'.$row['name'].'</th><th>'.$row['name'].'</th><th>'.$row['name'].'</td></tr>';
<?php }
echo '</tbody></table>'; ?>
This query print the result where rol = 1, but I need to show rol = 2 and rol = 3 too in the same result order (all users in rol 1, in rol 2 and in rol 3) inside of table, I think that I need a subquery in the same table (2 times more).
I need show the results like this:
MASTER
SUPERVISOR
NOOB
JOE BRUT
PEP ARIOLA
ANDY CHOLS
MAT GREEN
CARLA DIAZ
JOSE ZAVALA
There are fan post where not all the user role commented, so I don't want to show blank spaces...
Per example:
MASTER
SUPERVISOR
NOOB
JOE BRUT
PEP ARIOLA
JOSE ZAVALA
CARLA DIAZ
MAT GREEN
Best regards!

Related

Get members from each team via SQL JOINS

I have 3 tables, members, teams & team_members.
team_members houses the ids from both the members & teams and stores them per row.
The schema of theteam_members table:
teams table:
What I'd like to be able to do is create a join where i can output the team_name from the teams table and then underneth show the members_firstname associated with that that team. So example:
Team 1
joe bloggs
jon doe
Team 2
charlie chaplin
hulk hogan
My php code looks like this:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$sql = "SELECT t.team_name, group_concat(m.firstName)
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.teamname";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row["member_id"] . '<br>';
echo $row["team_id"] . '<br><br>';
}
}
?>
Now I get:
Notice: Trying to get property of non-object in -- on line 30 which is:
if($result->num_rows > 0){
You should use two joins to piece together the three tables.
SELECT t.team_name as team_name, group_concat(m.firstName) as team_members
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.team_name
You then should check the status of your query before trying to work with it.
if(!$result = $conn->query($sql)) {
die(printf("Errormessage: %s\n", $conn->error));
}
Then loop through the results, and split the grouped values by the comma.
while($row = $result->fetch_assoc()){
echo $row["team_name"] . '<br>';
$names = explode(',', $row['team_members']);
foreach($names as $name) {
echo $name . '<br>';
}
echo '<br>';
}
You also could use <br> as the separator in the group_concat. You can read more about that function here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat. If you did that you can get rid of the foreach and explode because the $row['team_members'] would be built with a linebreak for each member.
The easy way to do this in PHP is width two nested loops in first you go trought the team table and print it in the second you print all the playes width theat team id...
Something like:
do{
echo $row_team;
do{
echo $row_playa;
}while($row_plya = mysql_fetch_assoc($playas)); // whear pleya.team_id = $row_team.id
}while($row_team = mysql_fetch_assoc($teams));

MySql correct SELECT statement

I have two tables,
The first one:
things descriptions
------ ------------
First thing First description
Second thing Second description
Third thing Third description
Fourth thing Fourth description
...
The second one:
id products
-- --------
1 First product
2 Second product
3 Third product
4 Fourth product
...
I need a query to display the first two rows from the first table and then the first row of the second one, then the second two rows from the first table, then the second row of the second one and so on, obtaining this:
things+id prod+descr
--------- ----------
First thing First description
Second thing Second description
1 First product
Third thing Third description
Fourth thing Fourth description
2 Second product
...
How can I do it? Maybe with a UNION? Thank you very much!
Seems to me like the best practice here is to add another column to your first table that is a FK matching the PK of your first table. Would it be acceptable to have data like this? Then retrieve it in a program?
t2.ID t2.prod t1.thing t1.desc
------ ------- -------- -------------
1 first prod first thing first desc
1 first prod second thing second desc
UPDATE: based on your needs
// setup count
$countOuter = 0;
$countInner = 0;
//connect
$mysqli = mysqli_connect(localhost,user,pass,database);
// heres the tricky part you will have to make sure that your
// tables are filled out at a ratio of 2:1 or there could be an
// error thrown
// not sure if this is going to be necessary for your purposes
$sqlTest = "select * from tableOne"
$sqlTest2 = "select * from tableTwo"
$result1 = mysqli_query($mysqli, $sqlTest) or die (mysqli_error($mysqli));
$result2 = mysqli_query($mysqli, $sqlTest2) or die (mysqli_error($mysqli));
$rowsTableOne = mysqli_num_rows($result1);
$rowsTableTwo = mysqli_num_rows($result2);
// check ratio
if(($rowsTableOne / $rowsTableTwo) == 2)
{
while($countOuter < $rowsTableOne)
{
//outer query
$sqlOuter = "select * from tableOne LIMIT 2";
if ($count % 2 == 0) {
$sqlOuter .= " OFFSET ".$count;
}
$result = mysqli_query($mysqli, $sqlOuter) or die (mysqli_error($mysqli));
while($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
echo "<p>".$row[0]." ".$row[1]."</p>";
$countOuter++;
}
$sqlInner = "select * from tableTwo LIMIT 1";
if ($countInner != 1) {
$sqlInner .= " OFFSET ".$countInner;
}
$result = mysqli_query($mysqli, $sqlInner) or die (mysqli_error($mysqli));
while($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
echo "<p>".$row[0]." ".$row[1]."</p>";
$countInner++;
}
}
}
This should give you some general ideas, I did not have time to test it but it should point you in the general direction.

How to SELECT with a LIMIT while needing multiple rows with a same column value?

I have the following table as an example.
id uid car
1 3 BMW
2 3 AUDI
3 3 JEEP
4 5 MERC
5 6 BMW
6 6 FIAT
Now, I would like to get all cars but for only 2 users but don't know how many cars they have. When they all would have had only one car, I could just do a LIMIT 3 but how can I do this to get all the cars, but only for 2 users?
EDIT
If the 2 users are unknown you can use MySQL GROUP_CONCAT
$query = mysql_query("SELECT uid, GROUP_CONCAT(car) as cars FROM tablename GROUP BY uid ORDER BY uid ASC LIMIT 0,2");
while ($get = mysql_fetch_array($query)) {
$userid = $get['uid'];
$result = explode(",", $get['cars']);
echo '<h2>User #' . $userid . ' owns the following cars:</h2>' . "\n";
echo '<ul>' . "\n";
foreach ($result as $car) {
echo ' <li>' . $car . '</li>' . "\n";
}
echo '</ul>' . "\n";
}
Note: Don't forget to change the tablename in the SELECT query

Count rows in relational database

I have a coupon code site. I'm creating a "Black Friday" coupons and deals page.
In the sidebar I want the user to be able to see all the categories of coupons we have (apparel,shoes,electronics,etc.) and how many Black Friday coupons we have for each category.
I'm pulling in all the categories from the table "tblCategories", but what I'm having issues with is getting a count from the relational table "tblCouponsCategories" of how many coupons are in the "Black Friday" category, plus whatever other category I'm looking for. The categoryid from Black Friday is '24'. This is the code I have so far:
$result = mysql_query("SELECT name,fmtc_categoryid,categoryid FROM tblCategories ORDER BY name") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$fmtc_categoryid=$row['fmtc_categoryid'];
$categoryid=$row['categoryid'];
$name=$row['name'];
$result2 = mysql_query("SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' AND categoryid='$categoryid'") or die(mysql_error());
$count_coupons = mysql_num_rows($result2);
echo "<li><a href='http://www.mydomain.com/coupons/$fmtc_categoryid' title='View $name Coupon Codes'>$name ($count_coupons)</a></li>";
}
Here is what my relational table tblCouponsCategories is formatted like for a coupon that is both in the "Black Friday" category plus another category:
id couponid categoryid
83995 48312 5
83996 48312 9
83997 48312 14
83998 48312 11
83999 48312 24
84000 48312 38
I tink you have some mistake here:
SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' AND categoryid='$categoryid' GROUP BY categoryid") or die(mysql_error());
//should be
SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' GROUP BY categoryid") or die(mysql_error());

MySQL Select Prints TWO records twice?

MySQL Doubles my results?
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM cart_products WHERE cart_id=22");
while($row = mysql_fetch_array($result))
{
print("'.$row['name'].'<br/>");
}
mysql_close($con);
My database:
cart_id name
22 john
22 sarah
My printed HTML:
john<br />sarah<br />
john<br />sarah<br />
instead of
john<br />sarah
Why does it print four records ?
I second Tom's question. What happens when you run the SQL query from MySQL? Also, please do a print_r on the result and paste.
mysql_fetch_array() by default returns both a numeric and an associative array.
Call mysql_fetch_array($result, MYSQL_ASSOC) to get the expected result.