mysql query explode with two table join - php

my sql query
SELECT
team.id,
team.atitle,
team.etitle,
team.cup_id,
team.logo,
team.modarb,
team.count_id,
team.link AS tlink,
country.atitle AS name,
country.etitle AS ename,
cup.id AS catid,
cup.link,
cup.description,
cup.name AS cupname
FROM cup LEFT JOIN team ON (cup.id IN (". implode(', ', 'team.cup_id') ."))
LEFT JOIN country ON (country.id = team.count_id)
where cup.id='5'
row team.cup_id look like this 5, 4, 3,
need know how to use implode in mysql query

You should fix your data structure so you are not storing lists of ids as a string. Doing so is wrong, wrong, wrong:
It is wrong to store numbers as strings.
It is wrong to have ids in a table without properly declared foreign key references.
It is wrong to store lists in a single column, when SQL offers a great method for storing lists: a table.
Just in case you cannot fix the data structure, you can do:
FROM cup LEFT JOIN
team
ON find_in_set(cup.id, team.cup_id) > 0 LEFT JOIN
country
ON (country.id = team.count_id)
I only offer this as a stop-gap until you fix the data to be SQLish in form.

Related

How get table with references other table in yii2?

i have multiple table that join together and i need one query and get all references too ! is that possible in yii2??
get them in hierarchy array ??
How ???
Is it possible to do not use join???
thanks for your help!!!!
If you created the model classes for each table using Gii and selected to create the relations in the generated models, you can do something like the following.
1) In your Countries model just change the method that declares the relationship with Airports like this:
public function getAirports() {
return $this->hasMany(Airports::className(), ['country_id' => 'id'])->with('airlines');
}
2) When you do the query for the countries and you need to have the related airports, airlines and flightbooked do it like this:
$countries = Countries::find()
->where('something = something_else')
->with('airports')
->with('flightbooked')
->all();
This way you will get all the related models populated with way less queries to the database than using lazy-loading.
I just wanted to give a small suggestion:
As you are maintaining the relations in the tables and if you have generated your code using Gii, then that will generate the joins for you. You can then access any column of any table easily.
But I think UNION may not be an alternative to JOIN.
Maybe u can use union all for this. with this operator, you can concatenate the result sets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).
The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.
SELECT 'col1' AS source, col23, col343, col33, d FROM table1 WHERE ...
UNION ALL
SELECT 'col2', t2.fee, table2.fi, table2.fo, 'fum' FROM table2 JOIN table3 ON ...
UNION ALL
SELECT 'col3', '1', '2', buckle, my_shoe FROM table4
You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows. e.g:
select one.a
, SUM(one.b)
FROM (
SELECT 'q1' AS source, a, b, c, d FROM t1
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
) one
GROUP BY one.a
ORDER BY one.a
But i think joining tables more suitable. Hope help you

Separating comma broken words in PHP and selecting extra information

I've been trying to look into this for a while now but can't find an answer that explains the coding properly. Basically I have a mysql table with 'connections' relevant to a user. These connections are separated with a comma:
connection1, connection2, connection3, connection4, etc
What I need to do is to separate each one into an array like so:
$connection1
$connection2
$connection3
$connection4
Then for each of these I need to be able to select sertain information from a different table, so for example:
(SELECT name,id FROM users WHERE username = (all of the connections above))
Could any of you let me kow how this would be possible? Thank you
You can use FIND_IN_SET to do a JOIN, or you can join against a table of integers and use that with Substring_index to get the values from the CSV string
Normally a comma separated list in a database is the sign of poor design. Better to split them off into another table, with one row for each item in the comma separated list.
EDIT - Example of how to do it using a table of integers:-
SELECT name,id
FROM users a
INNER JOIN (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(concat(Connection, ','), ',', aCnt), ',', -1) AS aConnection
FROM Connections
CROSS JOIN (
SELECT a.i+b.i*10+c.i*100 + 1 AS aCnt
FROM integers a, integers b, integers c) Sub1
WHERE (LENGTH(Connection) + 1 - LENGTH(REPLACE(Connection, ',', ''))) >= aCnt) Sub2
ON a.username = Sub2.aConnection
This relies on a table called integers with a single column called i, with 10 rows with the values 0 to 9. You can cross join this against itself to get a range of numbers. In this case from 0 to 999, then limited by the number of commas in the field you are splitting up. This value is then used to find the commas for SUBSTRING_INDEX to split the string up.
It is simple. Use explode function of php.
$text= "connection1, connection2, connection3, connection4";
$res= explode(",",$text);
foreach($res as $i=>$id)
{
echo $res[$i];
}

PHP MySql: explode and JOIN Combination

I put user id with separate comma in MySql TABLE for best user. Example : 1,2,3 Now i work with PHP explode() function for this result:
$bestuser = explode(',',$bestuser);
i have another MySql TABLE for list of user with this row : id/name/datejoin/birthday ....
now, i need to print name of best user with MySql JOIN Methods. actually my mean how to combination explode result with other MySql TABLE result.
NOTE: i know this design(1,2,3) is bad, But I have no choice.
You could write an SQL query to do this:
SELECT id,name
FROM user
WHERE id IN (:yourListOfIds)
Be cautious of SQL injection if the list is at any way user supplied.
See this question, but if you look at the comments on the manual you'll find lots of people talking about exploding.
One can use MySQL's FIND_IN_SET() function in the join criterion:
table_a JOIN table_b ON FIND_IN_SET(table_a.id_a, table_b.csv_a)
However (per the warnings in my comments above) this operation will be terribly inefficient, as MySQL must fully scan both tables.
A much better solution would be to create a table of relations:
CREATE TABLE relations (
FOREIGN KEY (id_a) REFERENCES table_a (id_a),
FOREIGN KEY (id_b) REFERENCES table_b (id_b)
) SELECT table_a.id_a, table_b.id_b
FROM table_a JOIN table_b
ON FIND_IN_SET(table_a.id_a, table_b.csv_a);
ALTER TABLE table_b DROP csv_a;
Then one can query for required data by joining the tables as required:
SELECT table_a.*
FROM table_a JOIN relations USING (id_a)
WHERE relations.id_b = ?
If so desired, one could even use MySQL's GROUP_CONCAT() function to obtain the original CSV:
SELECT table_b.id_b, GROUP_CONCAT(relations.id_a) AS csv_a
FROM table_b JOIN relations USING (id_b)
WHERE ...
GROUP BY table_b.id_b

SQL join into array for each table

I am joining two tables: customers and queries.
I am getting the full_name from the customers table and the description from the queries table.
I am wondering if it is possible to have the results of an SQL join split into arrays that correspond with the table the data came from? For example:
$STH = $DBH->prepare("SELECT queries.description, customers.full_name FROM queries INNER JOIN customers ON queries.customer_id = customers.id");
$STH->execute();
$queries = $STH->fetchAll();
At the moment, I can access my data like this: $queries[0]['description'] and $queries[0]['full_name']
However, my question is whether there is an easy way to get the data like so: $job[0]['query']['description'] and $job[0]['customer']['full_name'].
Just as teresko mentioned, I can't understand why you'd need that.
I can only imagine you want to see on the PHP code what are the table that contained the information.
Maybe you could do something like SELECT queries.description as queries_description, then your php code would look like $queries['queries_description']. Would it be enough?
You can loop through the results in PHP and convert it to the data structure you want, but you cannot (as far as I know) automatically group the data into arrays based on the source table. A (somewhat messy) alternative, using SQL is to use a multi-query and create a temp table from your original results, then select the results on a per-table basis, like so:
CREATE TEMPORARY TABLE q AS
(SELECT queries.description, customers.full_name FROM queries
INNER JOIN customers
ON queries.customer_id = customers.id
);
SELECT q.description FROM q;
SELECT q.full_name FROM q;
So, in those SELECT statements, you'll have to list all the columns that you want for each result. Then in PHP, you'll have to iterate over each resultset and put the data into arrays (or objects/whatever) as needed. Errr. A fetchAll will still not get you what you want, but a fetchAll on the first non-empty resultset will get you all the rows from queries and the 2nd will get you all the rows from customers

How to pull row from join when foreign key is null

I have a DB table with product information, and a DB table with tax rates.
My problem is that I am joining these two tables together, which works great.. until I disable "taxable" on a row for the product DB. Now my query is trying to join, but doesn't find a foreign key and I get no result at all.. I want to grab a result either way. I am using code igniter syntax, but it should be pretty obvious whats going on here:
$this->db->from('inventoryTaxRates a');
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID');
sometimes q.inventyTaxRateID becomes 0, or disabled.. The query cannot join the two tables and gives me no result whatsoever. I want it to still give me the result from inventory_items.
I have tried left joining as well:
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID', 'left');
You can specify a RIGHT join like this:
$this->db->join('inventory_items q',
'q.inventoryTaxRateID = a.inventoryTaxRateID',
'right');
You can use RIGHT JOIN, but I'd like to rewrite query like that:
SELECT .. FROM inventory_items ...
LEFT JOIN inventoryTaxRates ...

Categories