Category Archives: MySQL

How to Solve can‘t connect to local mysql server through socket ‘/var/lib/mysql/mysql.sock‘

After the MySQL dataDir directory is migrated, the error prompts “can’t connect to local MySQL server through socket ‘/ var/lib/MySQL”/ mysql.sock ‘

solve:

Open my.cnf The changes are as follows:

[client]
port = 3306
socket = /new/mysql/ mysql.sock

[mysqld]

datadir=/new/mysql
socket=/new/mysql/ mysql.sock

View’s select contains a subquery in the from clause bug

View’s select contains a subquery in the FROM clause Summary of bug additions
0x00 The original intention of the article
This bug has been encountered before, but I have not been thinking deeply about it, and today I encountered it again.
0x01 bug simple description: the view contains subqueries in the clause
0x02 Detailed description of the bug (a little too much to highlight the bolded parts).
https://bugs.mysql.com/bug.php?id=12755
How to locate this bug
Search for view contains subquery, find the following bug (a circle…)
ErrorCode 1379: View’s SELECT still can’t contain a subquery
—————————————————————————
[3 May 2012 8:42] Arjan Saly
Description: Already reported in 2006 for version 5.0, still not solved in 5.5: When creating a view, subqueries are still not allowed in the SELECT clause. What’s the point of creating a view when it cannot contain complex queries? In my opinion a serious RDMBS SHOULD be able to accept complex queries, hence incuding subqueries, to keep these kind of queries maintainable. Wondering though: Do the developers really under estimate the importance of these requests? Or has it actually been solved in 5.5, but did I stumble into a bug for this particular distribution? How to repeat: create view Test as select TestNumber From ( select 0 as TestNumber union all select 1 as TestNumber union all select 2 as TestNumber union all select 3 as TestNumber ) TestNumbers
[4 May 2012 17:47] Sveta Smirnova
Please do not submit the same bug more than once. An existing bug report already describes this very problem. Even if you feel that your issue is somewhat different, the resolution is likely to be the same. Because of this, we hope you add your comments to the original bug instead. Thank you for your interest in MySQL. Duplicate of bug #12755
[7 May 2012 7:18] Arjan Saly
Don’t reply patronising like this as I could NOT find the original bug report using both google and your own search engine. I did find another one, but that one was from an older version (as is the one you mention) and was not open anymore. Replies like this do not motivate me to report other bugs or feature request, given the fact that apparently your search engine does not work. Nor do I feel taken seriously as we are talking about a request that is open for 7 years already!—————————————————————————-
Bug #12755 Subquery in FROM clause of views
—————————————————————————-
[23 Aug 2005 14:12] Kay Doebl
Description: You write in your MySQL Reference Manual :: 21.2 CREATE VIEW Syntax “A view definition is subject to the following restrictions: The SELECT statement cannot contain a subquery in the FROM clause.” … Do you intend to abolish this restriction and when? We would have the advantage, not to change our code to extend our database support at MySQL. How to repeat: Mail to: [email protected]
[4 Aug 2009 17:50] Valeriy Kravchuk
Bug #16757 was marked as a duplicate of this one.
[4 Aug 2009 17:57] Josh Duff
This bug: http://bugs.mysql.com/bug.php?id=16757&error=nd has many people requesting a fix – it really is a pain in the ass to work around. People are still posting comments on that duplicate now (it must come up higher in Google results or something). Please fix this? Pretty please?
[14 Aug 2009 20:54] HaiXin Tie
This most basic database feature has been requested by numerous users for over 5 years. A view without support of inner queries in the FROM clause can only be used as a toy, not in real world applications. This should be an essential part of any standard SQL implementation, and MySQL, though most widely used today, is the only one I know that doesn’t support it.
[17 Aug 2009 21:32] Eric Bergen
I took out the safety check and tried a few different types of queries and it seems to work fine in 5.0.27 (old I know). I think the only thing preventing this from being enabled is the check in sql_view.cc to prevent views being created on temporary tables. It just needs a way to distinguish between a sub query in the from clause and a real temporary table: /* is this table temporary and is not view? */ if (tbl->table->s->tmp_table != NO_TMP_TABLE && !tbl->view && !tbl->schema_table) {
[17 Aug 2009 21:53] HaiXin Tie
Nice!
[30 Oct 2009 21:39] Joseph Borge
This is what I have in the original 5.0.51b source: /* is this table temporary and is not view? */ if (tbl->table->s->tmp_table != NO_TMP_TABLE && !tbl->view && !tbl->schema_table) { my_error(ER_VIEW_SELECT_TMPTABLE, MYF(0), tbl->alias); res= TRUE; goto err; } I can not see the difference between Eric’s code and original code. What changes need to be made before this would work?
[7 Jun 2010 20:53] Mark Kendall
Bump, we’re investigating and attempting to add support for MySQL to a large Linux application designed for DB2. The lack of OLAP functions (specifically RANK() and DENSE_RANK()) was close to making this work not feasible but this BUG makes it a show stopper unfortunately.
[26 Mar 2011 19:45] Brian Slezak
What’s the status on this bug?
[20 Dec 2011 12:27] Arnaud Adant
You can always define another view for the subquery.
[4 May 2012 17:48] Sveta Smirnova
Bug #65185 was marked as duplicate of this one.
[7 May 2012 7:07] Arjan Saly
How about solving this bug for once? How can we ever take MySQL serious when subqueries are not allowed inviews AND this still isn’t solved 7 years (!!) after the bug has been reported?
[7 May 2012 7:10] Arjan Saly
Added a duplicate bug report because this one does NOT show up when searching either using Google or the Search engine of this site!
[2 Jul 2012 10:43] Stefan Haag
I stumbled upon this issue (again) using 5.5.21. While I see different workarounds, they are only that – workarounds. Obviously this is something coming up again and again for years. Would it be possible to have a developer commentating on this with someting more than “duplicate”? No offense. As mentioned before, the severity of this shouldn’t be S4, but more S2.
[12 Nov 2013 15:55] John Viescas
See also http://bugs.mysql.com/bug.php?id=70870. I’m happy to loudly add my voice to the clamour to have this fixed!
[9 Mar 2015 19:02] Roy Lyseng
Fixed in 5.7.7
[27 Mar 2015 2:59] Paul Dubois
Noted in 5.7.7, 5.8.0 changelogs. Previously, view definitions were not permitted to contain derived tables (subqueries) in the FROM clause. This restriction has now been lifted.
—————————————————————————-
0x03 Affecting version 5.0.7 – 5.7.6
0x04 Version changelog
Find a method:
https://dev.mysql.com/doc/

https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-7.html#mysqld-5-7-7-bug

Previously, view definitions were not permitted to contain derived tables (subqueries) in the FROM clause. This restriction has now been lifted.
Previously, derived tables (subqueries) or views in the FROM clause could not be merged into the outer query if they contained subqueries in the SELECT list. Instead, they were processed using materialization. This restriction has now been lifted so that queries previously executed using materialization can be executed more quickly using merging. (Bug #12755, Bug #11745276, Bug #60417, Bug #11865600)
0x05 Solution
(1) Upgrade mysql version to 5.7.7 and above
(2) Change the subquery to a combination of multiple views

Introduction to Relational Databases in SQL

1. You First Database1.1 Introduction to Relational Databases (video)1.2 Attributes of Relational Databases1.3 Query Information_Schema with SELECT1. 4 Tables: At the Core of Every Database (video)1.5 CREATE Your First Few TABLEs1.6 ADD a COLUMN with ALTER TABLEs1.7 Update Your Database as the Structure Changes (video)1.8 RENAME and DROP COLUMNs in Affiliations1.9 Migrate Data with INSERT INTO SELECT DISTINCT1.10 Delete tables with DROP TABLE
2. Enforce Data Consistency with Attribute Constrains2.1 Better Data Quality with Constrains (video)2.2 Types of Database Constrains2.3 Conforming with Data Types2.4 Types CASTs2.5 Working with Data Types (video)2.6 Change Types with ALTER COLUMN2.7 Convert Types USING a Function2.8 The Not-Null and Unique Constrains (video)2.9 Disallow NULL values with SET NOT NULL2.10 What Happens If You Try to Enter NULLs?2.11 Make Your Columns UNIQUE with ADD CONSTRAINT
3. Unique Identify Records with Key Constraints3.1 Keys and Superkeys (video)3.2 Get to Know SELECT COUNT DISTINCT3.3 Identify Keys with SELECT COUNT DISTINCT3.4 Primary Keys (video)3.5 Identify the Primary Key3.6 ADD Key CONSTRAINTs to the Tables3.7 Surrogate Keys (video)3.8 ADD A SERIAL Surrogate Key3.9 CONCATenate Columns to A Surrogate Key3.10 Test Your Knowledge before Advancing
4. Glue Together Tables with Foreign Keys4.1 Model 1:N Relationships with Foreign Keys (video)4.2 REFERENCE A Table with A FOREIGN KEY4.3 Explore Foreign Key Constrains4.4 JOIN Tables Linked by A Foreign Key4.5 Model More Complex Relationships (video)4.6 Add Foreign Keys to the “Affiliations” Table4.7 Populate the “professor_id” Column4.8 Drop “firstname” and “lastname”4.9 Referential Integrity (video)4.10 Referential Integrity Violations4.11 Change the Referential Integrity Behavior of A Key4.12 Roundup (video)4.13Count Affiliations Per University4.14 Join All the Table Together

1. You First Database
1.1 Introduction to Relational Databases (video)
1.2 Attributes of Relational Databases
1.3 Query Information_Schema with SELECT
information_schema is a meta-database that holds information about your current database. information_schema has multiple tables you can query with the known SELECT * FROM syntax:
tables: information about all tables in your current databasecolumns: information about all columns in all of the tables in your current database…
In this exercise, you’ll only need information from the 'public' schema, which is specified as the column table_schema of the tables and columns tables. The 'public' schema holds information about user-defined tables and databases. The other types of table_schema hold system information – for this course, you’re only interested in user-defined stuff.
Instruction 1
Get information on all table names in the current database, while limiting your query to the 'public' table_schema.

-- Query the right table in information_schema
SELECT table_name 
FROM information_schema.tables
-- Specify the correct table_schema value
WHERE table_schema = 'public';

Instruction 2
Now have a look at the columns in university_professors by selecting all entries in information_schema.columns that correspond to that table.

-- Query the right table in information_schema to get columns
SELECT column_name, data_type 
FROM information_schema.columns 
WHERE table_name = 'university_professors' AND table_schema = 'public';

Instruction 3
Finally, print the first five rows of the university_professors table.

-- Query the first five rows of our table
SELECT * 
FROM university_professors 
LIMIT 5;

1. 4 Tables: At the Core of Every Database (video)
1.5 CREATE Your First Few TABLEs
You’ll now start implementing a better database model. For this, you’ll create tables for the professors and universities entity types. The other tables will be created for you.
The syntax for creating simple tables is as follows:

CREATE TABLE table_name (
 column_a data_type,
 column_b data_type,
 column_c data_type
);

Attention: Table and columns names, as well as data types, don’t need to be surrounded by quotation marks.
Instruction 1:
Create a table professors with two text columns: firstname and lastname.

-- Create a table for the professors entity type
CREATE TABLE professors (
 firstname text,
 lastname text
);

-- Print the contents of this table
SELECT * 
FROM professors;

Instruction 2:
Create a table universities with three text columns: university_shortname, university, and university_city.

-- Create a table for the universities entity type
CREATE TABLE universities (
 university_shortname text,
 university text,
 university_city text
);

-- Print the contents of this table
SELECT * 
FROM universities;

1.6 ADD a COLUMN with ALTER TABLEs
Oops! We forgot to add the university_shortname column to the professors table. You’ve probably already noticed:

[How to Fix]Mybatisplus ignores mapped fields

In the development, we may encounter that mybatisplus uses entity class attribute for SQL operation. The entity has this attribute, but the database table does not have this field (that is, entity class attribute is not a database table field). If you don’t handle it, you will report an error.

FIRE

@TableName: Database Table Related

@TableId: table primary key identifier

@TableField: table field identifier

@TableLogic: Table field logical processing annotation (logical deletion

)
Solution

@TableField(exists = false): indicates that the property is not a database table field, but is required to be used.
 
@TableField(exists = true): indicates that the property is a database table field.

After adding this annotation to the attributes of the entity class, this field will not map to the database.

   @TableField(exist = false)
    private String deptName;

The attributes of Oracle batch modification sequence (such as cache)_size, increment_(by et al.)

Oracle self-growing columns can be set as sequences, such as self-growing IDs.

Create a sequence

--Create Sequence dept_deptid_seq
create sequence dept_deptid_seq
    increment by 10
    start with 1
    maxvalue 9990
    nocycle
    nocache

--Create default sequence no_no_seq
create sequence no_no_seq

Sequence (start with n) as the value of the first sequence, the sequence value (increment by n) for each of the increase, the maximum sequence as the maxvalue (n), the sequence of the minimum value for (minvalue n)
cycle said if the sequence of maximum value is greater than the start from the minimum cycle (the default is not cycle), database cache n said pre-allocated n values stored in memory (the default) 20
The query sequence
Note: After a sequence has been created, the value of the current sequence cannot be directly queryed.nextVal must be used to query the value of the next sequence before using currVal to query the value of the current sequence.

select sequence_name ,last_number, min_value,max_value,increment_by,cache_size from user_sequences

Modify the sequence

alter sequence sequence_name increment by 1 cache 3000

Batch modification sequence

--bulk change sequence
declare
  v_sql varchar2(2000);
  CURSOR seqs IS select sequence_name from user_sequences where user_sequences.CACHE_SIZE<=20  and user_sequences.LAST_NUMBER>10000;
begin
  FOR seq IN seqs LOOP
    v_sql:='alter sequence '||seq.sequence_name
           ||' increment by 1 cache 3000';
    dbms_output.put_line(v_sql);
    execute immediate v_sql;
  end loop;
end;

The cursor places the sequence to be modified. Loop out the sequence name and modify it.

The setobject() method reports an error. The parameter index out of range and MySQL syntax error exception report an error

SetObject() method, error Parameter index out of range and com. The MySQL. JDBC. Exceptions. Jdbc4. MySQLSyntaxErrorException error

Learn how to use the setObject() method in PreparedStatement for placeholders in SQL procedures. , appear when to replace the Parameter index out of range error:

1, the number of placeholders, and transfer the Object [] array element number
2, different placeholders used in Chinese?Rather than?

If the above situation is modified, the com. Mysql. JDBC. Exceptions. Jdbc4. MySQLSyntaxErrorException error
see first in the use of setObject () method before and after the difference between a PreparedStatement object:

Object[] objects = new Object[]{"name","age","xixi","23"};
sql = "insert into student (?,?) values(?,?);";
//Get the execution object (connection as Connection object)
preparedStatement = connection.preparedStatement(sql);
System.out.println(preparedStatement.toString());
// determine if the parameter exists, and replace it
if (obs!=null&&obs.length>0){
	for (int i = 0; i < obs.length; i++) {
		preparedStatement.setObject(i+1,obs[i]);
	}
}
System.out.println(preparedStatement.toString());

Perform before:
com. Mysql. JDBC. JDBC42PreparedStatement @ 443 b7951:
insert into student (* * NOT SPECIFIED, the NOT SPECIFIED) values (NOT SPECIFIED, the NOT SPECIFIED * *);

com after execution. Mysql. JDBC. JDBC42PreparedStatement @ 443 b7951:
insert into student (” name “, “age”) values (‘ hee hee ‘, ’23’);
All ** Not SPECIFIED ** placeholders are replaced by elements in the Objects[] array with single quotes.
in the mysql database, the parameters need to add single quotation marks, it is enclosed within a string value. Column names, table names, and so on use backquotes to distinguish them from special keywords (the symbol to the left of the 1 digit).
So if you want to replace non-attribute values, you should choose other methods such as concatenation SQL statements to prevent errors.

[How to Fix] Database can’t open file (errno:24)

Error: Unable to open database files while the database is running.
One, the problem report error two, the solution idea three, the treatment method

First, the problem report error
Can’t open file (errno:24)
Second, the solution
First we need to look at the error log of the database. Then determine whether the table is corrupt or a permission problem. There may also be insufficient disk space to properly access the table; Operating system limitations are also a concern; Use the perl error tool to see specific errors!

linux:/usr/local/mysql/bin # ./perror 24 
OS error code  24:  Too many open files 

Maximum number of open files exceeded! The maximum number of open files on the system is 65535. It cannot be exceeded! The maximum number of open files in the database must be out of limit! Show variables like ‘open_files_limit’; MySQL> reset MySQL = 2048; MySQL> reset MySQL = 2048;
Three, the treatment method

repair table ;

chown mysql Permissions

Clean up junk data from the disk

SQL Server Group sort de duplication row_ number() over ( PARTITION BY t1.col_ 2 ORDER BY 1 )

Recall SQLServer group sort once to reanalyze

row_number() over ( PARTITION BY t1.col_2 ORDER BY 1 )

-- Code
DELETE FROM table_name t 
WHERE t.rowid IN (
	SELECT rid
	FROM(
		SELECT t1.rowid rid,row_number() over ( PARTITION BY t1.col_2 ORDER BY 1 ) rn 
		FROM table_name t1 
	) t1 
	WHERE t1.rn > 1 
);

-- PARTITION BY t1.col_2
-- The first grouping is based on the second column

-- ORDER BY 1
-- then sort by the first column

-- row_number()
-- reassign row numbers to the grouped sorted data
-- similar to a grouped set of numbers
-- for example, the first two steps are divided into three groups
-- row_number() will renumber the first group from 1, 1.2.3.4 ....
-- the second group will still be numbered from 1, 1.2.3.4 ....
-- and so on down the line

-- WHERE t1.rn > 1
-- Filter the grouped sorted data to filter out all rows numbered greater than 1 (i.e. duplicate rows)
-- keep only the first record, filter all others greater than 1 and then use t.rowid IN () to delete them to achieve de-duplication

How to Check the most CPU consuming 50 queries in MYSQL

--Querying the 50 most CPU-intensive queries
SELECT TOP 50 
DB_NAME(dbid) AS DBNAME,
OBJECT_NAME(objectid,dbid) as OBJECTNAME,
total_worker_time/execution_count/1000/1000 AS [CPU Average execution (sec)],
    SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 
        ((CASE qs.statement_end_offset
          WHEN -1 THEN DATALENGTH(st.text)
         ELSE qs.statement_end_offset
         END - qs.statement_start_offset)/2) + 1) N'Execution Statements'
         ,st.text N'Full Words'
         ,total_worker_time/1000/1000 AS [Total CPU time consumed (seconds)]
         ,execution_count [number of runs]
 ,qs.total_worker_time/qs.execution_count/1000/1000 AS [average_execution_time_of_CPU(sec)]
 ,last_execution_time AS [last execution time]
 ,max_worker_time /1000/1000 AS [max_execution_time(sec)]
 ,total_physical_reads N 'total_physical_reads'
 ,total_logical_reads/execution_count N'number of logical reads per execution'
 ,total_logical_reads N'total_logical_reads'
 ,total_logical_writes N'total_logical_writes'
 ,*
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE last_execution_time> dateadd(minute,-100,getdate())
ORDER BY total_worker_time/execution_count DESC;
GO

Tkmybatis uses Example.SetOrderByClause Use for sorting and multiple sort fields

How to use it when sorting individual fields

example.setOrderByClause("user_type ASC"); //Output sorted by user type in ascending order

Running SQL looks something like this

SELECT ...
FROM tab_sy_user
order by user_type ASC 

The method of using when sorting multiple fields separated by a comma

The query results are sorted by the order in which the fields are sorted, and if the conditions are the same, continue the conditional sort by the next field until the last field sort is complete.

 //First according to user_type ascending ASC sorting, if there is the same condition, in accordance with the level condition descending DESC sorting
example.setOrderByClause("user_type ASC, level DESC");

Running SQL looks something like this

SELECT ...
FROM tab_sy_user
order by user_type ASC, level DESC