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
Related
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
I am using this code/query to delete bogus users using a list from 'bogus' table
and Obviously this query is not correct and shows error: Unknown column 'bogus.user' in 'where clause'
Consider that tables sample and bogus have ONLY ONE COLUMN each and I want to delete rows from sample table only retaining the data of table bogus.
delete from sample where sample.user=bogus.user;
How about:
delete from sample where sample.user in (SELECT user FROM bogus);
I think that's the savest way. It's probably possible to put both tables in a single statment without a join or nested select. But If you do that wrong you risk deleting both tables content. Thus I'd say it's better to do it this way.
You need to join for this
delete s from sample s
join bogus b on b.user = s.user
delete from sample where user in (select user from bogus)
I have two tables:
staticip has two columns: ip, staticipid
rm_users has many columns and one of it is staticipcpe
I would like to find rows in staticip table that is staticipid='2' and ip is not equal staticipcpe in table rm_users.
I tried the following sql statement but it didn't work.
$sqls="select s.ip, s.staticipid from staticip s
where s.staticipid='2' and not exists
(select u.staticipcpe from rm_users u
where u.staticipcpe=s.ip";
I have the following message
"Warning: mysql_result(): supplied argument is not a valid MySQL result resource"
Among other possible problems, you're missing a closing parenthesis:
$sqls="select s.ip, s.staticipid from staticip s
where s.staticipid='2' and not exists
(select u.staticipcpe from rm_users u
where u.staticipcpe=s.ip)";
Also, the mysql_* functions are deprecated. Use MySQLi or PDO.
if you query is right you can use NOT IN Clause to achieve your goal
like
Select Id
From Test
Where Id Not In( Select Foo From Bar )
see for more info
MySQL "NOT IN" query
Depending on your database a JOIN may be better over a sub-query (see Join vs. sub-query), and I also favor backticks (Importance of backtick around table name in MySQL query):
SELECT `s`.`ip`,`s`.`staticipid`
FROM `staticip` AS `s`
INNER JOIN `rm_users` AS `u`
ON `u`.`staticipcpe`<>`s`.`ip`
WHERE `s`.`staticipid`='2';
In plain English:
SELECT: grab the fields "ip" and "staticipid" from the result
FROM: the primary table will be "staticip" - alias as "s"
INNER JOIN: compare the rows in "staticip" with the rows in "rm_users"
ON (part of INNER JOIN): fetch the rows where "staticipcpe" from "ip" is not listed under the field "staticipcpe" from "rm_users"
WHERE: filter results such that the value of "staticipid" must be "2"
Don't forget to consider indexing the fields rm_users.staticipcpe, staticip.staticipid (I assume this one is already a PRIMARY KEY), and staticip.ip, otherwise you're looking at full table scans, rather than taking advantage of MySQL's b-tree lookup from memory.
I'm trying to create a mysql table from the inner join between two other tables. I'm dealing with a database someone creates which has the following tables:
sitematrix_sites
sitematrix_databases
They are related by another table (I don't know why don't use a foreign key) called sitematrix_sites_databases which has the following fields:
site_id and database_id.
That's how the two tables relate. Now I'm trying to remove that to make my life easier, so I have:
mysql> CREATE TABLE result AS(select * from sitematrix_databases INNER JOIN site
matrix_site_databases ON sitematrix_site_databases.database_id = sitematrix_data
bases.database_id);
ERROR 1060 (42S21): Duplicate column name 'database_id'
However, I'm getting that error. Does someone know how can I merge the two tables without repeating the database_id field?
Thanks
Remove the * in your SELECT statement and actually list out the columns you want in your new table. For columns that appear in both original tables, name the table as well (e.g. sitematrix_databases.database_id).
Don't use * instead name each column and use aliases. For instance instead of sitematrix_database.database_id you can have alternativeName. Also you can pick and choose which columns you want this way as well.
In SQL Server, you can use "select into". This might be equivalent syntax for mySql:
http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
Unfortunately, it's a two commands (not just one):
http://www.tech-recipes.com/rx/1487/copy-an-existing-mysql-table-to-a-new-table/
CREATE TABLE recipes_new LIKE production.recipes; INSERT recipes_new SELECT * FROM production.recipes;
Instead of using SELECT * ... try SELECT database_id ...
MySQL does not like joining tables that have the same column name.
I am building a site and i need to retrieve some information. I have this query.
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 ";
I need to add this other code:
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])."'
but it's not working...
i need to compare let's say the id of another table with the id of the current table... How to do that?
Thanks in advance...
You should learn something about joining tables...
Do not know what the relation is between the two tables (simply said: what column from one table is pointing to what column at other one), but try something similar (modification needed to meet You DB structure) - now lets assume both tables have related column called event_id:
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 cvistlsp22
LEFT JOIN civicrm_event ce ON ce.event_id = cvistlsp22.event_id
WHERE ce.title_en_US='".mysql_real_escape_string($_GET["titles"])."'";
civicrm_value_informazioni_su_tute_le_schede_p_22 table name is very long and You will not be able to create a table with such long name in other DBMS (e.g. ORACLE), so try to make it shorter while still self-describing...
If You want to join tables they have to have a relation, read more about relations and how to use them here: http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
You are retrieving the data from table civicrm_value_informazioni_su_tute_le_schede_p_22 in your query while the where clause you are adding, refers to the table civicrm_event. You need to add this new table in the from clause and do a join among the two tables using some common key. Example below:
$SQL = "
SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106, richiesta_ccnl_107, coop_va_109, nome_pdv_110, indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22
JOIN civicrm_event ON civicrm_value_informazioni_su_tute_le_schede_p_22.ID_PK = civicrm_event.ID_FK
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])
";
You need to replace the ID_PK and ID_FK with the relevant Primary and Foreign Keys that bind the tables together.
Please note using query params like that is not recommended. Please read PHP Documentation here for more explanation.